带有注释行的代码有效,但是包含那些行的代码无效.....为什么?以及如何解决? (注意:另一端运行的代码大致相同)
public void run() {
try {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream);
//ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
while (true) {
//System.out.println( ois.readUTF());
oos.writeUTF("hey");
}
} catch (Exception e) {e.printStackTrace(); }
}
编辑: 编写了一些代码以使其更清楚我的意思,是的,这有点混乱。 (无论是否有两个套接字,它似乎都不起作用):
Server.java(主要):
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(6666);
ServerSocket server2 = new ServerSocket(6667);
Socket socket = server.accept();
Socket socket1 = server2.accept();
OutputStream output = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(output);
ObjectInputStream ois = new ObjectInputStream(socket1.getInputStream());
while (true) {
System.out.println("server reading");
System.out.println( ois.readUTF());
System.out.println("server writing");
oos.writeUTF("hey");
}
} catch (Exception e) {e.printStackTrace(); }
}
Client.java(主要)
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 6666);
Socket socket1 = new Socket("127.0.0.1", 6667);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket1.getOutputStream());
while (true) {
System.out.println("client writing");
oos.writeUTF("yo");
System.out.println("client reading");
System.out.println( ois.readUTF() );
}
}
服务器:
server reading
客户:
client writing
client reading
答案 0 :(得分:1)
.flush()输出流。在写输出流后的示例中,我有:
oos.flush();
当我想确保消息已发送时,我应该一直保持刷新状态。