如何编写聊天客户端代码,以便它从服务器和控制台侦听输入?这是我当前的客户端,它成功发送并接受来自服务器的输入。正如您所看到的,它没有任何代码可以使它成功监听并接受来自控制台的输入,同时也可以从服务器打开输入。服务器输入将是来自其他聊天客户端的消息。从任何聊天客户端发送的消息将广播给所有其他客户端。我对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();
}
}
}
答案 0 :(得分:1)
如果您的主线程正在侦听来自服务器的输入,您可以启动另一个线程来继续侦听来自控制台的输入。您必须确保正确处理输入。可以设置某些标志以指示输入是来自服务器还是来自控制台。