java长连接例子_java实现长连接
();
public Client(String serverIp, int port) {
this.serverIp=serverIp;
this.port=port;
}
public void start() throws UnknownHostException, IOException {
if(running)return;
socket = new Socket(serverIp,port);
System.out.println("本地端口:"+socket.getLocalPort());
lastSendTime=System.currentTimeMillis();
running=true;
new Thread(new KeepAliveWatchDog()).start(); //保持長連接的線程,每隔2秒項服務(wù)器發(fā)一個一個保持連接的心跳消息
new Thread(new ReceiveWatchDog()).start(); //接受消息的線程,處理消息
}
public void stop(){
if(running)running=false;
}
/**
* 添加接收對象的處理對象。
* @param cls 待處理的對象,其所屬的類。
* @param action 處理過程對象。
*/
public void addActionMap(Classcls,ObjectAction action){
actionMapping.put(cls, action);
}
public void sendObject(Object obj) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(obj);
System.out.println("發(fā)送:\t"+obj);
oos.flush();
}
class KeepAliveWatchDog implements Runnable{
long checkDelay = 10;
long keepAliveDelay = 2000;
public void run() {
while(running){
if(System.currentTimeMillis()-lastSendTime>keepAliveDelay){
try {
Client.this.sendObject(new KeepAlive());
} catch (IOException e) {
e.printStackTrace();
Client.this.stop();
}
lastSendTime = System.currentTimeMillis();
}else{
try {
Thread.sleep(checkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
Client.this.stop();
}
}
}
}
}
class ReceiveWatchDog implements Runnable{
public void run() {
while(running){
try {
InputStream in = socket.getInputStream();
if(in.available()>0){
ObjectInputStream ois = new ObjectInputStream(in);
Object obj = ois.readObject();
System.out.println("接收:\t"+obj);
ObjectAction oa = actionMapping.get(obj.getClass());
oa = oa==null?new DefaultObjectAction():oa;
oa.doAction(obj, Client.this);
}else{
Thread.sleep(10);
}
} catch (Exception e) {
e.printStackTrace();
Client.this.stop();
}
}
}
}
}
總結(jié)
以上是生活随笔為你收集整理的java长连接例子_java实现长连接的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SVN中的回退操作
- 下一篇: 孪生网络(1)_孪生网络的分类