黑马程序员技术交流社区

标题: socket端给server端发送第二次消息就收不到,第三次就会报错 [打印本页]

作者: 362688114    时间: 2014-4-27 18:53
标题: socket端给server端发送第二次消息就收不到,第三次就会报错
class tcpSocket {
public static void main(String[] args) throws UnknownHostException, IOException {
  Socket soc=new Socket("10.10.1.172", 10001);  
  
  OutputStream out=soc.getOutputStream();
  
  BufferedReader read=new BufferedReader(new InputStreamReader(System.in));
  
  //InputStream input=soc.getInputStream();
  String line=null;
  while((line=read.readLine())!=null){
   if("886".equals(line))
    break;
    out.write(line.getBytes());
   // byte[] buf=new byte[1024];
   
   // int len=input.read(buf);
    //System.out.println(new String(buf,0,len));
  }
  read.close();
  soc.close();
}
}


class tcpServer {
public static void main(String[] args) throws IOException {
  ServerSocket server=new ServerSocket(10001);
  
  Socket soc=server.accept();
  
  String s=soc.getInetAddress().getHostAddress();
  
  System.out.println("已连接"+s);
  
  InputStream input=soc.getInputStream();
  
  byte[] buf=new byte[1024];
  int len=input.read(buf);
  System.out.println(new String(buf,0,len));
  
  /*
  OutputStream out=soc.getOutputStream();
  
  BufferedReader read=new BufferedReader(new InputStreamReader(System.in));
  
  String line=null;
  
  while((line=read.readLine())!=null){
   if("886".equals(line))
    //break;  
   byte[] by=new byte[1024];
   out.write(line.getBytes());
   }
  */
  
  //read.close();
  soc.close();
}
}


报错:Exception in thread "main" java.net.SocketException: Software caused connection abort: socket write error


作者: 钟成军    时间: 2014-4-27 20:03
将服务端改成这样就不会了
  1. public class TcpServer {
  2. public static void main(String[] args) throws IOException {
  3. ServerSocket server = new ServerSocket(10001);

  4. Socket soc = server.accept();

  5. String s = soc.getInetAddress().getHostAddress();

  6. System.out.println("已连接" + s);

  7. InputStream input = soc.getInputStream();

  8. byte[] buf = new byte[1024];
  9. int len = 0;
  10. while((len = input.read(buf))!=-1)
  11. System.out.println(new String(buf, 0, len));


  12. }
  13. }
复制代码






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2