0

我有一台服务器,我正在尝试向所有客户端发送一个特定的输入(字符串)。我的代码在这里:

serverSocket = new ServerSocket(SERVERPORT);
            while (true) 
                {
                    // listen for incoming clients
                    Socket client = serverSocket.accept();
                    mClients.add(client);                        
                    boolean finished = false;
                    try                             
                        {
                        for (int i=0; i<mClients.size(); i++) 
                        {
                            Socket well = mClients.get(i);
                            DataInputStream in = new DataInputStream(well.getInputStream());
                            PrintStream out = new PrintStream(well.getOutputStream());                                
                            // Print a message:
                            System.out.println("Client from : " + client.getInetAddress() + " port " + client.getPort());
                            // now get the input from the socket...                  

                                while(!finished) 
                                {
                                    String st = in.readLine();
                                    // Send the same back to client
                                    out.println(st);
                                    // Write it to the screen as well
                                    System.out.println(st);
                                    // If the input was "quit" then exit...
                                    if (st.equals("quit")) { finished = true; System.out.println("Thread exiting..."); }
                                }
                        }

看来我做错了什么。无论如何,我正在尝试将所有连接的套接字存储到一个向量中,然后将其中一个接收到的字符串发送给它们。这是正确的方法吗?

4

1 回答 1

0

在第一个 while(true) 语句中,仅侦听传入连接,然后创建一个单独的线程来处理该客户端连接。

从那里,您可以将在每个线程中创建的每个 outPutStream 添加到全局 ArrayList 中。遍历arrayList(使用字符串参数为此创建一个方法)并在所述方法中写入您想要的任何消息。

查看有关套接字通信的 Oracle 教程以获取帮助

于 2012-05-12T19:42:09.680 回答