简体   繁体   English

套接字不读取数据

[英]Socket is not reading data

I am trying a simple Java program to send and receive data... Server is sending the data and Client receives that... But this generates Socket Exception : Connection Reset 我正在尝试一个简单的Java程序来发送和接收数据...服务器发送数据,客户端接收到...但这会产生Socket异常:连接重置

This is my Server side code to sent Integer value... 这是我的服务器端代码发送的Integer值...

try {
   ServerSocket server = new ServerSocket(9089);

   Socket socket = server.accept();

   OutputStream out = socket.getOutputStream();
   out.write(12);
   out.flush();
   System.out.println("Data Sent....");
   Thread.sleep(5000);
} catch(Exception  e) {
   System.out.println("Server Error : " + e.toString());
}

This is my Client side code to receive that Int value... 这是我的客户端代码,用于接收Int值...

try {
   Socket client = new Socket(InetAddress.getLocalHost(), 9089);
   System.out.println("Connected ....");

   InputStream in = client.getInputStream();
   while(in.available()>0)
   {
      System.out.println("Unavailable...");
   }
   System.out.println("Received : " + in.read() );
   in.close();
} catch(Exception e) {
   System.out.println("Sender Error : " + e.toString());
}

In your client code I think you have to change the condition of the while loop: 在您的客户端代码中,我认为您必须更改while循环的条件:

while(in.available()==0) {
    System.out.println("Unavailable...");
}
System.out.println("Received : " + in.read() );
in.close()
   while(in.available()>0)
   {
      System.out.println("Unavailable...");
   }

This doesn't make any sense. 这没有任何意义。 available() returns the number of bytes that are available. available()返回可用的字节数。 If the result is positive, data is available, not unavailable. 如果结果是肯定的,则数据可用,不可用。

However this loop is completely pointless, and should just be removed completely. 然而,这个循环是完全没有意义的,应该完全删除。 The following read() will block as long as necessary. 只要有必要,以下read()将被阻止。

I would say this this code 我会说这个代码

while(in.available()>0)
{
    System.out.println("Unavailable...");
}

would cause an endless loop if data was available. 如果数据可用,将导致无限循环。

try 尝试

while(in.available() == 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM