0

你如何编写一个聊天客户端,以便它同时监听来自服务器和控制台的输入?这是我当前的客户端,它成功发送到服务器并接受来自服务器的输入。正如您所看到的,它没有任何代码可以使它成功地侦听和接受来自控制台的输入,同时也可以打开来自服务器的输入。服务器输入将是来自其他聊天客户端的消息。从任何聊天客户端发送的消息都会广播到所有其他客户端。我对 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();
        }
      }
}
4

1 回答 1

1

如果您的主线程正在侦听来自服务器的输入,您可以启动另一个线程来继续侦听来自控制台的输入。您必须确保正确处理输入。可以设置一些标志来指示输入是来自服务器还是来自控制台。

于 2013-04-07T06:04:52.217 回答