日期:2014-05-19  浏览次数:20906 次

java socket 服务端优化! 求高手
代码: public void run() {
try {
ServerSocket serversocket = new ServerSocket(8201);
while (true) {
socket = serversocket.accept();
SGIPCommand sgipcmd = new SGIPCommand();
DataInputStream in;

in = new DataInputStream(socket.getInputStream());

DataOutputStream out = new DataOutputStream(socket
.getOutputStream());
SGIPCommand cmd = sgipcmd.read(in);
int comandid = cmd.Bytes4ToInt(cmd.getCommandID());
System.out.println("#:" + comandid);
switch (comandid) {
case 1: 
Bind bind = (Bind) cmd;
BindResp bindresp = new BindResp(cmd.header.getUnicomSN());
bindresp.setResult((byte) 0);
bindresp.write(out, nodeid);
System.out.println("bind -- 已经连接");
break;
case 2: 
Unbind unbind = (Unbind) cmd;
UnbindResp unbindresp = new UnbindResp(cmd.header
.getUnicomSN());
unbindresp.write(out, nodeid);
System.out.println("unbind -- 断开连接");
break;
case 4:
Deliver deliver = new Deliver(cmd);
System.out.println("phone:" + deliver.getUserNumber());
System.out
.println("content:" + deliver.getMessageContent());
DeliverResp deresp = new DeliverResp(cmd.header
.getUnicomSN());
deresp.setResult((byte) 0);
deresp.write(out, nodeid);
break;
}

}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
  当代码如上的时候,由于客户端与服务端是几次对话,上述代码只能读取一次客户端的值,而且是反复读第一次对话内容,后面的内容不能读取,如果我把socket = serversocket.accept(); 这段代码放到循环外面就可以完成对话,不过完成对话后会话等待一会儿就会报错:
Exception in thread "Thread-0" java.lang.RuntimeException: java.net.SocketException: Connection reset
at com.ginkery.sgip.base.SGIPCommand.read(SGIPCommand.java:59)
at com.ginkery.sgip.smgoper.Recver.run(Recver.java:42)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.read(Unknown Source)
at com.ginkery.sgip.base.SGIPHeader.readHead(SGIPHeader.java:137)
at com.ginkery.sgip.base.SGIPCommand.read(SGIPCommand.java:56)
... 1 more

 

------解决方案--------------------
in = new DataInputStream(socket.getInputStream()), 会导主线程阻塞,一直读取客服端的数据,就能响应其他客户端的socket连接了,所以必须用多线程来解决:
while (true) {
Socket mySocket = myServerSocket.accept();
ExecutorService executorService = Executors
.newFixedThreadPool(8);
executorService.execute(new ServerHander(mySocket, savedir));
}
或者用nio来处理。