gpt4 book ai didi

java - 将客户端对象发送到服务器时出错

转载 作者:行者123 更新时间:2023-12-01 12:55:12 25 4
gpt4 key购买 nike

我无法通过客户端将对象发送到服务器,因为当我运行客户端时,服务器程序崩溃,导致出现“连接重置”错误

这是客户端:

    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

这有什么问题吗?

最佳答案

客户端没有关闭套接字,因此当服务器尝试读取不存在的第二个字符串时,服务器可以获得连接重置而不是 EOFException。

当您修复该问题时,EOFException 意味着没有任何内容可供读取。这不是问题。你只要捕获它,然后打破它。

关于java - 将客户端对象发送到服务器时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23968832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com