简体   繁体   English

如何使服务器能够接受来自具有不同套接字连接的客户端的多个输入流?

[英]How can I enable a server to accept multiple input streams from clients with distinct socket connections?

I'm trying to create a simple chat server that allows multiple distinct clients to chat with one another via the server output console. 我正在尝试创建一个简单的聊天服务器,该服务器允许多个不同的客户端通过服务器输出控制台彼此聊天。 The clients each with their own thread write to the server and can view the results on the server's standard output via the console. 每个具有自己线程的客户端都将写入服务器,并可以通过控制台在服务器的标准输出上查看结果。 However, I can't seem to get the BufferedReader to receive the messages coming from more than one client socket connection. 但是,我似乎无法让BufferedReader接收来自多个客户端套接字连接的消息。

Currently the first client thread gains exclusive access to the BufferedReader via it's socket. 当前,第一个客户端线程通过其套接字获得对BufferedReader排他访问。 However, I'd like multiple clients to connect to the server's input stream reader and have it wait for input from multiple client threads with distinct socket connections. 但是,我希望多个客户端连接到服务器的输入流读取器,并让它等待来自具有不同套接字连接的多个客户端线程的输入。 I would like clients to be able to post to the server at the same time. 我希望客户端能够同时发布到服务器。 How would I accomplish this with or without BufferedReader as my input stream reader? 在有或没有BufferedReader作为输入流阅读器的情况下,我将如何实现?

public class chatServer {

    public chatServer() throws IOException {

        int PORT = 8189;

        try (ServerSocket server = new ServerSocket(PORT)) {
            System.out.println("The server is running at "
                    + InetAddress.getByName(null) + "...");
            String rules = "The rules of this server are as follows:\n"
                    + "1.Respect your fellow chatters\n"
                    + "2.Vulgar language will result in punishment\n"
                    + "3.We reserve the right to ban you at any time.\n"
                    + "Enjoy!";

            System.out.println(rules + "\n");

            while (true) {
                try {
                    new clientHandler(server.accept()).run();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        chatServer cs = new chatServer();
    }

    class clientHandler implements Runnable {

        Socket socket;

        public clientHandler(Socket socket) {
            this.socket = socket;
        }

        public void run() {

            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));

                String line;
                while (true) {
                    line = in.readLine();
                    if ((line == null) || line.equalsIgnoreCase("exit")) {
                        // socket.close();
                    } else {
                        System.out.println(socket.getPort() + " > " + line);
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }
}

public class chatClient {

    private Socket socket;
    private String name = "";   
    private String IP = "127.0.0.1";
    private int PORT = 8189;


    public chatClient(String name, String IP, int PORT) throws UnknownHostException, IOException{

        this.name = name;
        socket = new Socket(this.IP,this.PORT);

    }

    public static void main(String[] args) throws UnknownHostException, IOException{

        chatClient c1 = new chatClient("John",null,0);
        chatClient.connect(c1);

    }

    public static void connect(chatClient cc) throws IOException {

        Socket socket = cc.socket; 
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.println("Welcome " + cc.name);

        String message = "";
        boolean done = false;
        Scanner stdin = new Scanner(System.in);
        System.out.println("Type your message here:");

        while(!done){
        System.out.print("> ");
        message = stdin.nextLine();
        out.println(message);

        if(message.trim().equalsIgnoreCase("exit")){
            done = true;
        }

        }
    }

}

Update: I'm looking for a suitable/alternative method to achieve the functionality of a Server that accepts multiple posts from various clients with distinct socket connections? 更新:我正在寻找一种合适/替代的方法来实现服务器的功能,该服务器可以接受来自具有不同套接字连接的各种客户端的多个帖子? If my current implementation cannot do so then how may I modify it to do so? 如果我当前的实现无法做到这一点,那么我该如何修改呢?

A BufferedReader is constructed around a single reader, which in turn is directly or indirectly connected to a single data source. BufferedReader围绕单个读取器构造,该读取器又直接或间接连接到单个数据源。 There is no way of changing that once constructed. 一旦构造,就无法更改。

In short your question doesn't make sense. 简而言之,您的问题没有任何意义。 Each client has a distinct socket, which in turn has its unique input and out out streams, which in turn must be wrapped in a distinct BufferedTeader per client. 每个客户端都有一个不同的套接字,该套接字又具有其唯一的输入和输出流,而每个客户端又必须将它们包装在不同的BufferedTeader Not one shared between all clients. 所有客户之间没有一个共享。

EDIT Your actual problem has nothing to do with BufferedReaders . 编辑您的实际问题与BufferedReaders无关。 It is here: 是这里:

new clientHandler(server.accept()).run();

You're running the handler inline instead of as a separate thread. 您正在内联而不是作为单独的线程运行处理程序。 run() should be run()应该是

new Thread(new clientHandler(socket.accept())).start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何处理从大厅服务器到客户端的多个流 - How to handle multiple streams from a lobby server to clients 如何使ServerSocket接受来自同一IP的多个连接? - How can I make ServerSocket accept multiple connections from same IP? 如何使多个客户端与服务器通信? - How to enable multiple clients to communicate with the server? 如何为多个客户端创建套接字服务器 - how to make a socket server for multiple clients 如何仅使用localhost(Java)中的套接字接受连接? - How do I have a socket accept connections only from the localhost (in Java)? 如何在Java服务器上接受多个套接字连接 - How to accept multiple socket connection at Java server 如何获得多个(UDP)客户端以仅接收来自特定服务器的数据包? - How can I get multiple (UDP) clients to only receive packets from a specific server? 如何使用套接字处理连接到服务器的多个客户端? - How can I handle multiple clients connected to a server using sockets? 服务器套接字和多个客户端可以在单个主机上运行吗? - Can Server Socket and multiple clients run on a single host? 如何准确测量服务器可以处理多少个套接字连接? - How can I accurately measure how many socket connections my server can handle?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM