我正在練習一個簡單的java程序,我正在演示簡單的客戶機服務器交互。來自服務器的消息的第一部分被傳送。然後程序繼續運行,不執行?我們是否需要爲每個單獨的流量創建一個新的套接字?客戶機/服務器編程
Server代碼
server = new ServerSocket(4587);
System.out.print("Starting the Server on port " + server.getLocalPort() + "\n");
System.out.println("Waiting for client...");
Socket client = server.accept();
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader br1 = new BufferedReader(new InputStreamReader(client.getInputStream()));
br.write("Hello, you are connected to Server. What is your name?");
br.write("\n");
br.flush();
while((s=br1.readLine())!=null)
{
}
br.write("Thank you ");
br.newLine();
br.flush();
}
客戶端代碼
String stdin;
System.out.println("Attempting to connect to " + hostname + ":" + port);
client = new Socket("localhost", 4587);
System.out.println("Connection Established");
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((stdin = br.readLine()) != null) {
System.out.println(stdin);
}
BufferedWriter br1 = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
br1.write("Mike");
br1.write("\n");
br1.flush();
while ((stdin = br.readLine()) != null) {
System.out.println(stdin);
}
服務器輸出
Starting the Server on port4587
Waiting for client....
客戶端輸出
Attempting to connect to :123
Connection Established
Hello you are connected to Server, What is ur name
如果這可以幫助..在這兩個循環之後
爲什麼向下票呢?他表現出了努力。 – bblincoe
好吧,恕我直言,這個問題是以模糊的方式報道的,並且沒有明確提及代碼。 –