服务端在readLine客户端数据的时候阻塞了,关闭客户端后才接受到数据,不知道什么原因,请高手们帮帮忙,代码如下:
package com.example.qmik.framework; import java.io.BufferedOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.util.ArrayList; import java.util.List; /* * 功能:客户端连接监听器 * 时间:2013/06/07 * 作者:M1301001 */ public class IoSocketListener implements Runnable { private List<Socket> socketList=new ArrayList<Socket>(); private int serverPort=17171; private ServerSocket socket; public IoSocketListener(){ try { this.socket=new ServerSocket(this.serverPort); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { try { while(true){ Socket client = this.socket.accept(); this.socketList.add(client); SocketAddress caddress=client.getRemoteSocketAddress(); String ip=caddress.toString(); this.sendMsg(client,ip); Thread h=new Thread(new IoClientListener(client)); h.start(); } } catch (IOException e) { e.printStackTrace(); } } /* * 释放资源 */ public void onDestroy(){ if(this.socket!=null){ try { for(Socket item:this.socketList){ item.close(); } this.socket.close(); } catch (IOException e) { return; } } } /* * 发送消息到客户端 */ public synchronized void sendMsg(Socket client,String msg) { try { BufferedOutputStream out = new BufferedOutputStream(client.getOutputStream()); out.write(msg.getBytes("utf-8")); out.flush(); } catch (Exception e) { e.printStackTrace(); } } }
package com.example.qmik.framework; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; /* * 功能:客户端消息监听器 * 时间:2013/06/07 * 作者:M1301001 */ public class IoClientListener implements Runnable { Socket client; public IoClientListener(Socket client) { this.client=client; this.run(); } @Override public void run() { while (true) { try { DataInputStream in =new DataInputStream(client.getInputStream()); String msg=null; String s; while((s = in.readLine())!=null){ msg+=s; } if(msg!=null){ sendMsg(msg); } else{ if(!client.isConnected()){ client.close(); } break; } } catch (IOException e) { e.printStackTrace(); break; } } } /* * 发送消息到客户端 */ public synchronized void sendMsg(String msg) { try { DataOutputStream out=new DataOutputStream(client.getOutputStream()); out.write(msg.getBytes("utf-8")); out.flush(); } catch (Exception e) { e.printStackTrace(); } } }
请帮帮忙什么改?
这个问题你解决了,同问下这个问题啊
同问,求解答
我是新手,服务和客户端两个工程和你所发的数据不是一个编码而且在代码里强制转换所发消息的编码的时候,就会出现这个情况。比如我工程是UTF-8,客户端发送汉字,代码都是正的,就是收不到数据,然后发句英文才可能会接受到,而且本次英文会加在上次str的后面。希望这个BUG能够有人解决。还有就是客户端发送消息的时候flush。别的情况我就不懂了。