我将在 2 个 Android 设备之间用 Java 创建简单的聊天。我找到了简单的服务器脚本,但我是编程套接字的新手。
问题:我想从客户端 A 接收消息并发送给客户端 B。
我知道如何为同一个客户端创建“回声”响应,但如何向另一个客户端发送消息?
现在服务器看起来像这样:
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(19198);
Socket connectionSocket = welcomeSocket.accept();
while(true)
{
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}