你如何编写一个聊天客户端,以便它同时监听来自服务器和控制台的输入?这是我当前的客户端,它成功发送到服务器并接受来自服务器的输入。正如您所看到的,它没有任何代码可以使它成功地侦听和接受来自控制台的输入,同时也可以打开来自服务器的输入。服务器输入将是来自其他聊天客户端的消息。从任何聊天客户端发送的消息都会广播到所有其他客户端。我对 Java 还是很陌生,即使我感觉答案会非常明显,但我完全被困住了。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClientMain
{
public static void main(String[] args) throws UnknownHostException, IOException
{
//DNS of Chat Server
final String HOST = "localhost";
//Port number for chat server connection
final int PORT = 6789;
Socket serverSocket = new Socket(HOST, PORT);
try
{
//Will need three streams for communication: console-client, client-server, server-client
PrintWriter toServer = new PrintWriter(serverSocket.getOutputStream(), true);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
//User must be logged in; any username is acceptable
System.out.print("Enter username > ");
toServer.println("LOGIN " + fromUser.readLine());
String serverResponse = null;
while((serverResponse = fromServer.readLine()) != null)
{
System.out.println("Server: " + serverResponse);
if(serverResponse.equals("LOGOUT"))
{
System.out.println("logged out.");
break;
}
System.out.print("command> ");
toServer.println(fromUser.readLine());
}
toServer.close();
fromServer.close();
fromUser.close();
serverSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}