碰到个项目 要用java来做后台数据传输。其中一个多个后台程序和java使用tcp来链接
@Controller
public class TCPCommunicateQTCode {
private static Logger log = Logger.getLogger(ConfigServiceImpl.class);
private final int MAX_LENGTH = 1024;
private final int PORT = 9002;//TCP端口
private ServerSocket tcpSocket = null;
private BufferedWriter bw = null;
private Socket socket;
private InputStream in;
@PostConstruct
public void start() {
log.info("服务器开启tcp服务");//运行
init();
new Thread(new Runnable() {
public void run() {
//调用服务器套接字对象中的方法accept()获取客户端套接字对象
while(true) {
try {
//等待服务器链接 accept是阻塞的,作为服务器,需要一直等待客户端链接
socket = tcpSocket.accept();
String ip=socket.getInetAddress().getHostAddress();
int prot=socket.getPort();
log.info("有客户端连接,ip"+ip+",prot"+prot);
if(ip.equals("192.168.1.101") && prot==9021) {
//开启一个线程 准备接收数据
TCPAcceptData tcpAcceptData = new TCPAcceptData(socket);
tcpAcceptData.start();
}else if(ip.equals("192.168.1.100") && prot==9021) {
//需要处理业务逻辑
}
//客户端连接收,定时向客户端发送心跳包
TCPSendData tcpSendData = new TCPSendData(socket);
tcpSendData.forSendDate();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}).start();
}
/**
* @Description 连接初始化
*/
private void init(){
try {
tcpSocket = new ServerSocket(PORT);
log.info("服务器开启TCP服务 启动成功");
} catch (Exception e) {
tcpSocket = null;
System.out.println("服务器开启TCP服务 启动失败!");
e.printStackTrace();
}
}
}
/**
* 接受数据的类
*/
public class TCPAcceptData extends Thread {
private int MAX_LENGTH=1024;
private Socket socket;
private InputStream in;
public TCPAcceptData(Socket socket) {
this.socket=socket;
try {
in=socket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run(){
while(true) {
try {
byte[] data=new byte[MAX_LENGTH];
int len=in.read(data);
if(len==-1) {
System.out.println("服务断开");
return;
}
String text = new String(data, 0, len);
System.out.println(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 发送心跳包的类
*/
public class TCPSendData {
private Socket socket;
private OutputStream out;
// OutputStream out=socket.getOutputStream();
// out.write("收到".getBytes());
public TCPSendData(Socket socket) throws IOException {
this.socket=socket;
this.out=socket.getOutputStream();
}
public void SendDate(String data) throws IOException {
out.write(data.getBytes());
}
public void forSendDate() {
new Thread(new Runnable() {
public void run() {
try {
while(true) {
Thread.sleep(2000);
out.write("ok".getBytes());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
}