我正在编写一个简单的程序,以使用TCP协议将对象表单服务器发送到客户端。我正在使用ObjectInputStream和ObjectOutputStream发送和接收对象。我在互联网上完全按照一些示例代码进行操作,但仍然出现此错误。这是我的代码。希望你们能帮助我
客户:
public class Client {
private Socket socket;
private ObjectInputStream receiveWeather;
public Client() {
try {
socket = new Socket("localhost", 4000);
receiveWeather = new ObjectInputStream(socket.getInputStream());
Weather w = null;
try {
w = (Weather) receiveWeather.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(w.getDescription());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Client();
}
}
服务器:
public class Server {
ServerSocket server;
ObjectOutputStream sendWeather;
Socket socket;
Weather w;
public Server() {
try {
server = new ServerSocket(4000);
socket = server.accept();
sendWeather = new ObjectOutputStream(socket.getOutputStream());
w = WeatherInfo.getWeatherInfo("Ha Noi"); // this line just get object w from my function
sendWeather.writeObject(w);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Server();
}
}
错误:
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.peek(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.peek(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at App.Client.<init>(Client.java:18)
at App.Client.main(Client.java:29)