JAVA中的通信主要靠java.net和java.nio包中的类实现,下面我将演示如何利用java.net包中的类来模拟一个用于收发报文的长连接服务器。
服务器的功能:
1. 接收来自客户端的请求报文
2. 检测报文是否符合规范
3. 返回应答报文给客户端
实例代码如下:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @description
* @version 2015年1月26日 下午2:10:39
*/
public class CoreSimulate implements Runnable {
private final int port;
private final String responseFileName;
public CoreSimulate(int port, String responseFileName) {
this.port = port;
this.responseFileName = responseFileName;
}
public static void main(String[] args) {
if(args.length < 2) {
System.out.println("请输入参数:1:监听端口 2:返回报文文件名");
}else {
new Thread(new CoreSimulate(Integer.parseInt(args[0]), args[1])).start();
}
}
public void run() {
try {
System.out.printf("核心模拟器启动成功,监听端