Connection reset by peer: socket write error. What is wrong with my Java code

旧时模样 提交于 2019-12-02 00:49:35
while (socket.isConnected()) {

The problem is here.

  1. There is no reason for the while loop in the first place. It's a login message: it only needs to be sent once. The server almost certainly isn't expecting a second one from a logged-in connection, so it is closing.

  2. isConnected() is not a valid test for the connection still being present. The only valid test is the absence of an IOException such as the one you're getting, which means the peer has closed the connect. And when you get such an exception, all you can do is close the socket and stop trying. Retrying is pointless: the connection has gone.

Socket.isConnected() only tells you about the state of the Socket. Not of the connection. You connected this socket, so it's connected.

NB You should use the same streams for the life of the socket, not create a new one per message.

@EJP @weston The issue has been resolved after much hit & trial. The working code is as follows:

Socket socket = new Socket("mshxml.abcd.com", 8999, InetAddress.getLocalHost(), 8999);
OutputStream outStream = socket.getOutputStream();

  try {
   String STX =  new Character((char) 2).toString();
   String ETX =  new Character((char) 3).toString();
   OutputStreamWriter osw = new OutputStreamWriter(outStream);
   BufferedWriter bw = new BufferedWriter(osw);

   bw.write( STX + "username=fred&password=abcd" + ETX ); 
   bw.flush();
} catch (Exception e) {
    e.printStackTrace();
}

But I have zero idea why is this code working and the original was not. Any suggestions would be much appreciated. And many thanks for bearing with my queries and duplicate posts. :)

@EJP regarding your thought about server closing the connection between receiving STX and next line, you are right. The server didnt close the connection right away; it was only during debugging (when the server got enough time to analyse the bytes) that I noticed it was doing so.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!