日期:2014-05-20  浏览次数:20762 次

java socket通讯问题!急啊!!!!
现在的情况是,客户端发送数据,服务器只监听到一次,当客户端第二次发送数据的时候,服务器监听不到了,那个socket我也没有断开,大概代码如下,请各位高手帮看看!



服务器端:


public TCPOptClass() {
  try {
  serverSocket = new ServerSocket(1234);
  } catch (IOException ex) {
  System.out.println("初始化TCP操作类失败!");
  }
  }

//接收数据函数(这个函数是放到线程中实时接收客户端数据,但只能收到客户端的第一次数据,第二次以后就接收不到了)
public String recvData(){
  String datastr="";

  try {
  socket = serverSocket.accept();

  in = new DataInputStream(socket.getInputStream());
  out = new DataOutputStream(socket.getOutputStream());

  int c = -1,count = 0;
  while((c = in.read()) != 0)
  {
  this.buf[count] = (byte)c;
  count++;
  }
  datastr = new String(this.buf, 0, count);
  } catch (IOException e) {
  System.out.println("接收数据失败!");
  }

  return datastr.trim();
  }
//发送数据(这个是往客户端发送数据,没什么可说的了)
public void SendData(String aSendData,String aHostIP)
  {
  if(aSendData.equals("")) return;
  String senddata = aSendData+":serverdata";
  try { Thread.sleep(2000); } catch (InterruptedException ex) { }

  try {
  out.write(senddata.getBytes());
  out.flush();
  } catch (UnsupportedEncodingException e) {
  System.out.println("发送数据失败!");
  } catch (IOException e) {
  System.out.println("发送数据失败!");
  }
  }  



客户端代码:
public tcpOptClass(String curServerIP) {
  this.buf = new byte[this.buflength];
 
  try {
client = new Socket(InetAddress.getByName(curServerIP), this.serverPort);

this.in = new DataInputStream(client.getInputStream());
this.out = new DataOutputStream(client.getOutputStream());
  } catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
  }
//接收数据(这个是放到线程中实时接收服务器返回的数据)
public String recvData()
  {
  String data = "";
 
  try {
  if(!client.isConnected()) return data;
  if(this.in == null) return data;
  int c = -1,count = 0;
  while((c = this.in.read()) != 0)
  {
  this.buf[count] = (byte)c;
  count++;
  }
  data = new String(this.buf, 0, count);
  } catch (IOException e) {
  System.out.println("接收数据失败!");
  }
 
  return data.trim();
  }
//发送数据(这个是往服务器发送数据请求,这个发送操作只在程序刚开始启动后发送就成功,再第二次发送服务器就收不到了)
public String SendData(String aSendData,String aHostIP)
  {
  String senddata = aSendData, data="";
try {
this.out.write((senddata).getBytes());
this.out.flush();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
  }


以上的代码没有任何异常,就是客户端刚启动后发送的数据服务器才收得到,再发送服务器就收不到任何数据了。

------解决方案--------------------
你的服务器端的accept也放线程里面了

socket = serverSocket.accept();