我会更好地解释我的问题,并且我会预防性地对我糟糕的英语表示抱歉。我正在练习 java.net 包(这是我下一次大学考试的论点),我正在尝试更好地控制客户端和服务器设备之间的通信。更准确地说,我尝试使用 TCP 连接在 3 个不同的时间从服务器到客户端发送 3 个不同的字符串,然后再调用相关 Socket 的 close() 方法。我发现我的脚本没有按我预期的方式工作。在客户端,我收到所有 3 个字符串,但仅在关闭套接字时才收到。相反,我希望在将所有 3 条消息放入服务器的输出流后立即接收它们。我将发布服务器脚本的代码。
在批评我之前,我读了this在写新问题之前提出问题,但这并没有解决我的问题 下面的脚本是管理服务器端连接的线程的 run() 方法的主体。
try{
//Dormi per un pò..
System.out.println("Il Client con ip "+ind+" ed associato all' Handler #"+id+" è in attesa");
Thread.sleep(5000);
PrintWriter pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
pw.println("Hi "+ind); //ind is the InetAddress of the connected client
pw.flush();
Thread.sleep(5000);
pw.write("what's up?\n");
pw.flush();
Thread.sleep(5000);
pw.write("I gotta go. Bye\n");
pw.flush();
pw.close();
s.close();
System.out.println("Il Client associato all'Handler #"+id+" si è disconnesso");
}catch(Exception e){
e.printStackTrace();
}
这是客户端代码:
package socket;
import java.net.*;
import java.io.*;
public class MultiThreadClient extends Thread{
private byte[] address={(byte) 192, (byte)168, (byte) 1, (byte)15};
private int destPort=2000;
public MultiThreadClient(){
super();
}
public void run(){
try{
InetAddress ip=InetAddress.getByAddress(address);
Socket s=new Socket(ip,destPort);
s.setReuseAddress(true);
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
String message1=br.readLine();
String message2=br.readLine();
String message3=br.readLine();
System.out.println(message1);
System.out.println(message2);
System.out.println(message3);
s.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[]args){
//for(int i=0;i<3;i++){
MultiThreadClient mtc=new MultiThreadClient();
mtc.start();
// }
}
}
最佳答案
您的代码工作得很好 - 您只需在 readLine
方法上阻塞 3 次,然后打印您的响应(此时套接字在服务器端关闭)。
试试这个:
String message1 = br.readLine();
System.out.println(message1);
String message2 = br.readLine();
System.out.println(message2);
String message3 = br.readLine();
System.out.println(message3);
我的另一个技巧是在 finally
block 中进行清理。
try { ... }
catch { ... }
finally {
s.close();
}
这样,即使抛出异常,资源也会被清理。
关于java - 我可以在关闭Socket之前通过TCP发送数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50820267/