问题描述
我正在尝试从独立的Java应用程序创建和维护与主机的TCP连接。
I am trying to create and maintain a TCP connection to a host from a standalone java application.
本地端口和服务器端口相同= 8999.
连接后,我必须向服务器发送一个消息:< STX> username = fred& password = abcd< ETX> 。
Local port and server port is same = 8999.After connection, I have to send a msg to the server: < STX >username=fred&password=abcd< ETX >.
套接字创建和消息发送的代码如下:
The code for socket creation and message sending goes like:
Socket socket = new Socket("mshxml.abcd.com", 8999, InetAddress.getLocalHost(), 8999); OutputStream outStream = socket.getOutputStream(); while (socket.isConnected()) { try { int stx = 2, etx = 3; DataOutputStream dout = new DataOutputStream(outStream); dout.writeByte(stx); dout.writeBytes("username=fred&password=abcd"); dout.writeByte(etx); } catch (Exception e) { e.printStackTrace(); }
但连接不会持续存在。在调试时,我发现以下错误:
But the connection does not persist. On debugging, I find the following error:
java.net.SocketException: Connection reset by peer: socket write error at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(Unknown Source) at java.net.SocketOutputStream.write(Unknown Source) at java.io.DataOutputStream.writeBytes(Unknown Source) at com.voya.socketprog.CClient.createConnection(CClient.java:120) at com.voya.socketprog.CClient.createSocket(CClient.java:33) at com.voya.socketprog.CClient.main(CClient.java:138) Line 120 is: dout.writeBytes("username=fred&password=abcd");
注意:当我连接到我的机器上的虚拟服务器(localhost)时,同样的程序运行成功能够接收和发送消息。
Note: This same program runs successfully when connected to a dummy server (localhost) on my machine where I am able to receive and send messages.
请帮忙。
推荐答案
while (socket.isConnected()) {
问题在这里。
-
循环时没有理由第一名。这是一条登录消息:它只需要发送一次。服务器几乎肯定不会期望从登录连接中获得第二个,因此它正在关闭。
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.
isConnected() 不是仍然存在的连接的有效测试。唯一有效的测试是没有 IOException ,例如您正在获得的那个,这意味着对等方已关闭连接。当你得到这样的例外时,你所能做的只是关闭套接字并停止尝试。重试毫无意义:连接已经消失。
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()仅告诉您套接字的状态。不是连接。您已连接此套接字,因此已连接。
Socket.isConnected() only tells you about the state of the Socket. Not of the connection. You connected this socket, so it's connected.
NB您应该在套接字的生命周期中使用相同的流,而不是为每条消息创建一个新流。
NB You should use the same streams for the life of the socket, not create a new one per message.
这篇关于通过对等方重置连接:套接字写入错误。我的Java代码有什么问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!