我正在建立基本的客户端-服务器连接。 该代码可以正常工作,但是客户端在关闭连接之前只能发送1条消息并接收其修改。 如何使它发送和接收多条消息?
我想到了使用while循环,但我不知道如何正确实现它。 我需要能够发送多个消息以保持一致的连接
下面的代码是客户端向服务器发送字符串,服务器将其转换为大写。
//Server:
public class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
if(clientSentence.toUpperCase().trim().contentEquals("QUIT")) {
connectionSocket.close();
}
}
}
}
//Client:
public class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
Socket clientSocket = new Socket("LocalHost", 6789);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.print("Enter characters to be capitalized: ");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
}
}
此代码的输出为:
Enter characters to be capitalized: hi
FROM SERVER: HI
答案 0 :(得分:0)
您的服务器只能从每个客户端获取一条消息,因为在while循环中,您每次调用welcomeSocket.accept()
时都需要迭代。这意味着您的服务器代码将停止,直到获得新的客户端连接为止。
如果希望服务器支持多个客户端,请考虑使用多线程。例如,看看:on this post