我有一台服务器,我正在尝试向所有客户端发送一个特定的输入(字符串)。我的代码在这里:
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..."); }
}
}
看来我做错了什么。无论如何,我正在尝试将所有连接的套接字存储到一个向量中,然后将其中一个接收到的字符串发送给它们。这是正确的方法吗?