我无法添加ObjectInputStream
来读取用户的输入,它总是在这一点上阻塞。如果我删除服务器中应该从用户读取输入然后发送硬编码字符串的ObjectInputStream
,则此代码工作正常。幕后发生了什么?我知道,当创建ObjectOutputStream
时,它会发送一个标头,当创建ObjectInputStream
时,它会读取该标头。在尝试实例化oOISUser
之前,我需要在System
中刷新某些内容吗?
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public Server() {
ServerSocket oSS = null;
Socket oS = null;
ObjectOutputStream oOOS = null; // to write to socket
ObjectInputStream oOIS = null; // to read from socket
ObjectInputStream oOISUser = null; // to read input from user
try {
oSS = new ServerSocket(1025);
oS = oSS.accept();
oOOS = new ObjectOutputStream(oS.getOutputStream());
oOIS = new ObjectInputStream(oS.getInputStream());
oOISUser = new ObjectInputStream(System.in);`// doesn't get past this
String sToSend = (String) oOISUser.readObject();
System.out.println("server says: " + sToSend);
oOOS.writeObject(sToSend);
oOOS.flush();
System.out.println("server receives: " + (String) oOIS.readObject());
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
} finally {
try {
if (oSS != null) oSS.close();
if (oS != null) oS.close();
if (oOOS != null) oOOS.close();
if (oOIS != null) oOIS.close();
if (oOISUser != null) oOISUser.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) {
Server s = new Server();
}
}
这是客户端的代码:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class Client {
public Client() {
Socket oS = null;
ObjectOutputStream oOOS = null;
ObjectInputStream oOIS = null;
try {
oS = new Socket("127.0.0.1", 1025);
oOOS = new ObjectOutputStream(oS.getOutputStream());
oOIS = new ObjectInputStream(oS.getInputStream());
System.out.println("client receives: " + (String) oOIS.readObject());
String sToSend = "hello from client";
System.out.println("client says: " + sToSend);
oOOS.writeObject(sToSend);
oOOS.flush();
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
} finally {
try {
if (oS != null) oS.close();
if (oOOS != null) oOOS.close();
if (oOIS != null) oOIS.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) {
Client c = new Client();
}
}
new ObjectInputStream(System.in)
你在问题中自己说的:
当创建 ObjectInputStream 时,它会读取该标头
因此,您实际上是在等待用户在控制台中输入 ObjectInputStream 标头。这种情况发生的可能性非常小(除非文件通过管道传输到 System.in(。从 System.in 读取序列化的 Java 对象几乎没有意义。用户不可能在控制台中键入有效的序列化 Java 对象。不过,他/她可以键入文本。因此,请使用阅读器或扫描仪。