由于TCP通信短连接在一次读写操作后关闭链接
而建立链接需要3次握手,而释放时需要4次握手
在一个客户端与服务器频繁通信时采用短连接是非常消耗资源和消耗时间的
更多参考http://www.cnblogs.com/beifei/archive/2011/06/26/2090611.html
所以此时采用长连接比较合理,以下是亲自测试过的TCP长连接
Client代码:
import java.io.OutputStream;
import java.net.Socket;
public class TCPClientTest {
private static final int SERVER_PORT=2010;
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", SERVER_PORT);
System.out.println("Connected to server...sending command string");
OutputStream out = socket.getOutputStream();
int i = 0;
while (i < 10) {
out.write(("test" + i).getBytes()); // 发送
out.flush();
Thread.sleep(1000);
i++;
}
out.close();
socket.close();
}
}
Server代码:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
public class TCPTransport {
private static final int SERVER_PORT=2010;
private static Hashtable<String, Socket> ht = new Hashtable();
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("VNTCenter.main()===TCP SERVER==============");
ServerSocket vntServer = null;
try{
vntServer= new ServerSocket(SERVER_PORT);
System.out.println("Listening Port is "+vntServer.getLocalPort()+"...");
while(true){
Socket vntClient=vntServer.accept();
System.out.println("have a client entering , the IP is "+vntClient.getInetAddress()+"...");
System.out.println("have a client entering , the Port is "+vntClient.getPort()+"...");
new GetGpsThreadFun(vntClient).start();
ht.put(vntClient.getInetAddress().toString(),vntClient);
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
vntServer.close();
}
}
}
class GetGpsThreadFun extends Thread{
private Socket vntThreadClient;
public GetGpsThreadFun(Socket vntThreadSocket){
vntThreadClient=vntThreadSocket;
}
public void run(){
try{
byte[] data = new byte[128];
while(true){
int len = vntThreadClient.getInputStream().read(data);
if (len > 0){
System.out.println(vntThreadClient.getInetAddress()+":"+vntThreadClient.getPort()+":"+new String(data,0,len));
if("shutdown".equals(vntThreadClient)){
break;
}
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}