随机套接字异常:连接重置
正如我在question中提到的,我收到了SocketException:Connection Reset。
在实施了Aaron的回答后,它似乎如预期的那样工作。但今天我再次运行代码时,再次收到连接重置错误。
问题是,如果我运行我的代码5次,它似乎工作2/5次,其余的给我错误...
服务器:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket server = new ServerSocket(444);
while (true) {
Socket socket = server.accept();
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
Object objRead = objIn.readObject();
if (objRead != null) {
System.out.println(objRead);
}
}
}
}
客户端:
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.HashMap;
public class Client {
public static void main(String[] args) throws IOException {
Socket sock;
int port = 444;
HashMap<Integer, String> mapSend= new HashMap<>();
mapSend.put(1,"row1");
mapSend.put(2,"row2");
sock = new Socket(InetAddress.getLocalHost(), port);
ObjectOutputStream objOut = new ObjectOutputStream(sock.getOutputStream());
objOut.writeObject(mapSend);
objOut.flush();
}
}
这是错误:(在我运行客户端之后,它出现在服务器的输出上):
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at java.io.ObjectInputStream$PeekInputStream.read(ObjectInputStream.java:2308)
at java.io.ObjectInputStream$BlockDataInputStream.read(ObjectInputStream.java:2716)
at java.io.ObjectInputStream$BlockDataInputStream.readFully(ObjectInputStream.java:2740)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1978)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1913)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at java.util.HashMap.readObject(HashMap.java:1154)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1017)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1891)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at iotest.Server.main(Server.java:16)
在客户端,我没有收到任何错误。
编辑
有什么办法可以调试客户端-服务器吗?这可能会给你们提供更多关于这方面的信息。
解决方案
关闭输出流,而不是只刷新它。
NB ReadObject()不返回NULL,除非您写为NULL。这个测试毫无意义。
相关文章