简体   繁体   English

如何在Java客户端服务器程序中将消息发送到多个客户端

[英]How do i send the message to multiple clients in java Client-Server Program

Multiple Clients say(A, B, C, D etc) make connection to one server through same socket. 多个客户端说(A,B,C,D等)通过同一套接字连接到一台服务器。 They all send messages to server as and when required. 它们都在需要时将消息发送到服务器。 Client messages are sent only to server(and not to other clients). 客户端消息仅发送到服务器(而不发送给其他客户端)。 But whenever server sends a message it should be delivered to all the clients. 但是,每当服务器发送消息时,都应将其传递给所有客户端。 Please help me out jam only able to get server message on only 1 client 请帮我解决,只能在1个客户端上获取服务器消息

//MultithreadedServer.java //MultithreadedServer.java

package server;
import java.io.*;

import java.net.*;
import java.util.ArrayList;
import java.util.Vector;
public class MultithreadedServer
{



Vector<ClientHandler> clients = new Vector<ClientHandler>();
    Vector<String> users = new Vector<String>();
    private static ServerSocket servSocket;
    private static final int PORT = 1247;

public MultithreadedServer() throws IOException{
    servSocket = new ServerSocket(PORT);
  while(true) {

                Socket client = servSocket.accept();
                System.out.println("\nNew client accepted.\n");




    ClientHandler handler;
        handler = new ClientHandler(client);
        clients.add(handler);

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

}
class ClientHandler extends Thread
{

private Socket client;
private BufferedReader in;
private PrintWriter out;
String name,message,response;

public ClientHandler(Socket socket)
{
    //Set up reference to associated socket...
    client = socket;
    try
    {
        in = new BufferedReader(
                new InputStreamReader(
                        client.getInputStream()));
        out = new PrintWriter(
                    client.getOutputStream(),true);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    start();
}
public void sendMessage(String  msg)  {
        System.out.println("is it even coming here?");
    out.println("Server:" + msg);
}
public void boradcast(String message)  {
    // send message to all connected users
    for (ClientHandler c : clients) {

          c.out.println("Server: hello");
}
}
public String getUserName() {  
        return name; 
    }
 public void run()
  {
    try
    {
        String received;
        do
        {   System.out.println("Enter Your Message: ");
            String msg = in.readLine();
            out.println(msg);
            boradcast("testing");
            received = in.readLine();
            out.println("ECHO: " + received);
        //Repeat above until 'QUIT' sent by client...

        }while (!received.equals("QUIT"));
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            if (client!=null)
            {
                System.out.println(
                            "Closing down connection...");
                client.close();
                        }
        }catch(IOException e)
        {
            e.printStackTrace();
        }
      }
   }
}}
//ClientProgram

import java.io.*;
import java.net.*; 
public class Client
 {
private static InetAddress host;
private static final int PORT = 1247;
private static Socket link;
private static BufferedReader in;
private static PrintWriter out;
private static BufferedReader keyboard; 
public static void main(String[] args)  throws IOException
{
    try
  {
        host = InetAddress.getLocalHost();
        link = new Socket(host, PORT);
        in = new BufferedReader(
                new InputStreamReader(
                            link.getInputStream()));
        out = new PrintWriter(
                            link.getOutputStream(),true);
        keyboard = new BufferedReader(
                        new InputStreamReader(System.in));
        String message, response;
        do
        {
            System.out.print(
                  "Enter message ('QUIT' to exit): ");
            message = keyboard.readLine();
           //Send message to server on
            //the socket's output stream...
            out.println(message);
            //Accept response frm server on
            //the socket's input stream...
            response = in.readLine();
            //Display server's response to user...
            System.out.println(response);
        }while (!message.equals("QUIT"));
    }
    catch(UnknownHostException uhEx)
    {
        System.out.println(
                    "\nHost ID not found!\n");
    }
    catch(IOException ioEx)
    {
        ioEx.printStackTrace();
    }
    finally
    {
        try
        {
            if (link!=null)
            {
                System.out.println(
                        "Closing down connection...");
                link.close();
            }
        }
        catch(IOException ioEx)
        {
            ioEx.printStackTrace();
        }
       }
      }
   }

An obvious way to do this would be to cycle through all ClientHandlers in clients and send the message to each of them: 一种明显的方法是遍历客户端中的所有ClientHandler并将消息发送给每个客户端:

for (ClientHandler ch : clients){
    ch.sendMessage(message); //Or something
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM