【发布时间】:2018-02-26 18:27:32
【问题描述】:
我想将一个对象从我的客户端发送到我的本地主机服务器以添加到数据库中,并将结果发送回该对象是否发送成功。对象已成功发送,但我的服务器没有将结果发送回客户端,并导致我的客户端框架表单因等待服务器响应而挂起。我不知道我的代码有什么问题。你能告诉我一些解决这个问题的方法吗?
这是发送结果的函数:
public void sendResult(String result) {
try {
Socket clientSocket = myServer.accept();
System.out.println("Connected to client");
ObjectOutputStream os = new ObjectOutputStream(clientSocket.getOutputStream());
os.writeObject(result);
System.out.println("Result sent");
} catch (Exception ex) {
ex.printStackTrace();
}
}
调用发送结果函数的地方:
public void service() {
try {
if (receiveStudent() != null) {
Student std = receiveStudent();
if (dao.addStudent(std)) {
System.out.println("OK");
sendResult("OK");
} else {
System.out.println("FAILED");
sendResult("FAILED");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
另外,在Service函数中,控制台打印“OK”,表示满足if条件。
接收学生方法:
public Student receiveStudent() {
Student s = new Student();
try {
Socket clientSocket = myServer.accept();
System.out.println("Connect to client successfully");
ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
Object o = ois.readObject();
if (o instanceof Student) {
s = (Student) o;
return s;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
【问题讨论】:
-
显示 ReceiveStudent() 方法的代码
-
sendResult()方法等待客户端连接到它,因为accept()。应该反过来,服务器应该连接到客户端。 -
@LucianovanderVeekens 这意味着我必须再次将客户端重新连接到服务器?
-
@BrotherEye 你应该重用你在
receiveStudent()中获得的clientSocket来发回响应。 -
@LucianovanderVeekens 我注意到您的评论,并将客户端套接字作为服务器类的属性添加为全局变量,现在可以使用。非常感谢!但是现在我必须重新输入两次表格才能成功添加对象。这是某种延迟还是我的代码有问题?