我正在构建一个简单的Java服务器,该服务器使用两个ServerSocket实例同时在两个端口上同时侦听客户端请求。这是服务器的代码:
import java.io.PrintWriter; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; class Socket1 implements Runnable { public void run() { try { ServerSocket serverSock=new ServerSocket(5000); while(true) { Socket sock=serverSock.accept(); PrintWriter writer=new PrintWriter(sock.getOutputStream()); String text="Welcome to Port 5000"; writer.println(text); } } catch(Exception e) { System.out.println("Error"); } } } class Socket2 implements Runnable { public void run() { try { ServerSocket serverSock=new ServerSocket(3000); while(true) { Socket sock=serverSock.accept(); PrintWriter writer=new PrintWriter(sock.getOutputStream()); String text="Welcome to Port 3000"; writer.println(text); } } catch(Exception e) { System.out.println("Error"); } } } public class Server { public static void main(String[] args) { Socket1 s1=new Socket1(); Socket2 s2=new Socket2(); Thread t1=new Thread(s1); Thread t2=new Thread(s2); t1.start(); t2.start(); } }
现在为Client1编码:
import java.io.InputStreamReader; import java.io.BufferedReader; import java.net.Socket; public class Client1 { public static void main(String[] args) { try { Socket s=new Socket("127.0.0.1", 5000); InputStreamReader streamReader=new InputStreamReader(s.getInputStream()); BufferedReader reader=new BufferedReader(streamReader); String text=reader.readLine(); System.out.println(text); reader.close(); } catch(Exception e) { System.out.println("Error"); } } }
Client2包含与Client1相同的代码,唯一的区别是它尝试连接到端口3000。现在,我首先使用命令提示符执行Server.java。服务器阻塞时,我打开两个单独的命令提示符,并在一个命令提示符下执行Client1.java,在另一个命令提示符下执行Client2.java。但是,两个客户端都进入阻塞状态,但我没有任何输出。知道如何解决这个问题吗?
PrintWriter由defaut缓冲。在之后添加一个writer.flush()(或更好的a,close()因为您不再使用流)writer.println()。
writer.flush()
close()
writer.println()