我无法通过客户端向服务器发送对象,因为当我运行客户端时,服务器程序崩溃让我“连接重置”错误
这是客户:
public class Client {
public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException{
Socket s = new Socket("192.168.1.3", 4444);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
Group g = new Group("EXAMPLE");
String command = "ADD_GROUP";
System.out.println("Sending: " + command);
oos.writeUTF(command);
oos.flush();
oos.writeObject(g);
oos.flush();
s.close();
}
}
这是服务器:
public class Server{
public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException, ParseException
{
ServerSocket server = new ServerSocket(4444);
System.out.println("Waiting for clients to connect...");
SimpleDataSource.init("database.properties");
Network net = new Network();
while (true)
{
Socket s = server.accept();
InetAddress clientAddress = s.getInetAddress();
System.out.println("Incoming connection from: " + clientAddress.getHostName() + "[" + clientAddress.getHostAddress() + "]");
ServiceClass service = new ServiceClass(s,net);
service.doService();
}
}
}
这是ServiceClass类:
public class ServiceClass{
private Socket s;
private Network net;
public ServiceClass(Socket s, Network net){
this.s = s;
this.net = net;
}
public void doService() throws IOException, SQLException, ClassNotFoundException, ParseException
{
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
while(true){
String line = (String) ois.readUTF();
System.out.println("Received: " + line);
if(line.equals("ADD_GROUP")){
Group group = (Group) ois.readObject();
net.addGroup(group);
}
}
}
}
当我运行服务器时,它等待客户端连接,当我运行我的客户端程序服务器崩溃时,我遇到了这个错误:
Waiting for clients to connect...
Incoming connection from: UNKNOWN_DEVICE[192.168.1.3]
Received: ADD_GROUP
Error: Group already exists
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:340)
at java.io.ObjectInputStream$BlockDataInputStream.readUnsignedShort(ObjectInputStream.java:2808)
at java.io.ObjectInputStream$BlockDataInputStream.readUTF(ObjectInputStream.java:2864)
at java.io.ObjectInputStream.readUTF(ObjectInputStream.java:1072)
at social_network.ServiceClass.doService(ServiceClass.java:35)
at social_network.Server.main(Server.java:39)
Java Result: 1
这有什么问题?
答案 0 :(得分:1)
客户端没有关闭套接字,因此当服务器尝试读取不存在的第二个字符串时,服务器可以获得连接重置而不是EOFException。
当您解决此问题时,EOFException意味着没有任何内容可供阅读。这不是问题。你抓住它,然后休息。