Java如何保持socket的长连接

写道
package com.yihongyu.exec.modules.crx.service.impl;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yihongyu.exec.modules.crx.manager.CrxNotificationManager;
import com.yihongyu.exec.modules.crx.service.CrxNotificationService;
import com.yihongyu.exec.modules.crx.service.CrxSocketClientService;
@Service
public class CrxSocketClientServiceImpl implements CrxSocketClientService {

private ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);

@Autowired
private CrxNotificationService crxNotificationService;

private Socket socket;
private Properties props = new Properties();
private String host;
private String portStr;
/**初始化Socket连接信息*/
@Override
@PostConstruct
public void init() {
try {
props.load(new FileInputStream("conf/notifications/crx.properties"));
host = props.getProperty("crx.host", "192.168.1.225");
portStr = props.getProperty("crx.port", "8222");
Integer port = Integer.parseInt(portStr);
connect(host, port);
} catch (FileNotFoundException e) {
LoggerFactory.getLogger(getClass()).error("无法找到Crx服务器配置文件,请检查是否存在文件:conf/notifications/crx.properties!");
} catch (IOException e) {
LoggerFactory.getLogger(getClass()).error("装载Crx服务器配置文件失败:conf/notifications/crx.properties!", e);
}
}

/**创建Socket连接*/
@Override
public Boolean connect(String host, int port) {
try {
destroy();
this.socket = new Socket(host, port);
if(!isOrNotServerClose()){
System.out.println("----------------Connection Crx socket success!----------------");
}else{
System.out.println("----------------Connection Crx socket fail!----------------");
LoggerFactory.getLogger(getClass()).error("Connection Crx socket fail!");
}
socket.setSoTimeout(60000);
socket.setKeepAlive(true);
isServerClose();
return socket.isConnected();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
return false;
}
}

/**检测服务端Socket是否断开*/
@Override
public void isServerClose(){
executor.schedule(new Runnable() {
@Override
public void run() {
try {
System.out.println("=================sendUrgentData=================");
socket.sendUrgentData(0XFF);
isServerClose();
} catch (IOException e) {//出现异常,服务端主动断开
destroy();
isServerClose();
LoggerFactory.getLogger(getClass()).error("Crx Server Exception Close!");
LoggerFactory.getLogger(getClass()).error("重新向服务端发起连接");
reConnect();//重新向服务端发起连接
e.printStackTrace();
}
}
}, 10000, TimeUnit.MILLISECONDS);

}

/**重新创建连接*/
@Override
public boolean reConnect() {
try {
Integer port = Integer.parseInt(portStr);
this.socket = new Socket(host, port);
if(!isOrNotServerClose()){
System.out.println("----------------Connection Crx socket success!----------------");
}else{
System.out.println("----------------Connection Crx socket fail!----------------");
LoggerFactory.getLogger(getClass()).error("Connection Crx socket fail!");
}
socket.setSoTimeout(60000);
socket.setKeepAlive(true);
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
return false;
}
}

@Override
public Boolean isOrNotServerClose() {
try {
socket.sendUrgentData(0XFF);
return false;
} catch (IOException e) {//出现异常,服务端主动断开
LoggerFactory.getLogger(getClass()).error("Crx Server Exception Close!");
e.printStackTrace();
return true;
}
}

/**向Crx服务端发送信息*/
@Override
public String process(String contentXml) {
try {
System.out.println("Send CrxNotification Xml: " + contentXml);
if(contentXml!=null && contentXml.length()>0){
OutputStream out = this.socket.getOutputStream();
out.write(contentXml.getBytes("GBK"));
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

/**获取Crx服务端返回的信息*/
@Override
public String getCrxMsg() throws UnsupportedEncodingException, IOException{
//服务端返回的消息状态: 0--发送成功, 1--发送失改, 2--超时
String crxServerMsg = null;
InputStream in =socket.getInputStream();
if (in.available()>0)
{
byte[] buff = new byte[in.available()];
in.read(buff);
crxServerMsg = new String(buff);
}
return crxServerMsg;
}

/**关闭socket*/
@Override
public void destroy() {
try {
if(this.socket!=null){
this.socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

 

你可能感兴趣的:(socket)