服务器发送消息从一个客户端连接到所有连接的客户端。 JAVA

时间:2014-05-04 04:30:51

标签: java client-server

我正在编写服务器/客户端聊天,其中基本上多个客户端连接到一个服务器。一个客户端向服务器发送消息然后所有其他客户端将收到相同的消息。例如:客户端A,B,C连接到同一服务器。客户端A向服务器发送消息,然后服务器将相同的消息发送到客户端B和C,但不包括客户端A.

我被困在服务器向所有其他客户发送消息的部分。

下面是代码,我只是一个Java初学者,所以对代码的任何帮助都会非常感激。

服务器侧

public class ServerP2P extends Thread{
private ServerSocket server = null;
private Socket clientSocket = null;
private ArrayList<ServerThread> clientThreadList = new ArrayList<>();
private int maxClient = 4;
private int port = 9990;
boolean listening = true;

    public ServerP2P(){
        try{
            server = new ServerSocket(port);
        }catch(IOException e){
            e.printStackTrace();
            return;
        }
        System.out.println("Server with Port "+port+" is Up and Running");
    }

    public void run(){
        System.out.println("Room Chat Is Up");
        while(listening){
            for(int i = 0;i<clientThreadList.size();i++){
                if(!clientThreadList.get(i).getConneection()){
                    System.out.println(clientThreadList.get(i)+" is removing from server because there is no conntection");
                    clientThreadList.remove(i);
                }
            }
            try{
                clientSocket = server.accept();
            }catch(Exception e){
                e.printStackTrace();
            }
            System.out.println("User with IP "+clientSocket.getInetAddress()+" Has Connected to Server");
            clientThreadList.add(new ServerThread(clientSocket));
            try{
                Thread.sleep(200);

            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
    public ArrayList<ServerThread> listOFClient(){
        return clientThreadList;
    }
    public static void main(String[] args){
        ServerP2P server = new ServerP2P();
        server.start();
    }

}

ServerThread

 public class ServerThread{
private Socket clientSocket;
private boolean connected;
private Incomming incommingData;
String msg = null;

    private class Incomming extends Thread{
        private DataInputStream input;
        public void run(){
            try{
                input = new DataInputStream(clientSocket.getInputStream());
            }catch(IOException e){
                e.printStackTrace();
                return;
            }
            System.out.println("User with IP "+clientSocket.getInetAddress()+" has connected");
            while(true){
                try{
                    Thread.sleep(200);
                    int msgSize = input.readInt();
                    byte[] msgByte = new byte[msgSize];
                    for(int i = 0; i < msgSize ; i++){
                        msgByte[i] = input.readByte();
                    }
                    msg = new String(msgByte);
                    System.out.println(msg);

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

    public ServerThread(Socket newClientSocket){
        this.clientSocket = newClientSocket;
        connected = true;
        incommingData = new Incomming();
        incommingData.start();
    }

    public boolean getConneection(){
        return connected;
    }
    public void closeConnection(){
        try{
            connected = false;
            clientSocket.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}

客户机侧

public class ClientP2P{

private  Socket serverSocket = null;;
private  DataOutputStream output = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(
        System.in));

public static void main(String[] args) {
    ClientP2P client = new ClientP2P();
    client.startConnect();;
}
public void startConnect(){
    int port = 9990;
    try {
        serverSocket = new Socket("localhost", port);
        System.out.println(serverSocket.isBound());
        output = new DataOutputStream(serverSocket.getOutputStream());
        System.out.println("Please Enter Your name: ");
        String nameClient = reader.readLine();
        output.writeInt(nameClient.length());
        output.writeBytes(nameClient);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("You Are Connected");
    System.out.println("Chat Can Start");
    sendText();
}
public void sendText(){
    try {
        while (true) {
            System.out.println("Type Message: ");
            String msg = reader.readLine();
            output.writeInt(msg.length());
            output.writeBytes(msg);
            System.out.println("Message sent");
            recivedText();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public void recivedText(){
    try{
    DataInputStream input = new DataInputStream(serverSocket.getInputStream());
    int textSize = 0;
    while(input.available() != 0){
        byte[] byteString = new byte[textSize];
        for(int i = 0; i < textSize;i++){
            byteString[i] = input.readByte();
        }
        String txtServer = new String(byteString);
        System.out.println(txtServer);
        textSize = 0;
    }
    sendText();
    }catch(Exception e){
        e.printStackTrace();
    }
}

}

感谢你们的时间。

2 个答案:

答案 0 :(得分:0)

您的ServerThread收到邮件,并且您希望将其发送给所有其他客户。您可以实现的一种方法是让客户端向服务器注册自己(这有助于服务器在启动时不知道客户端,理想情况应该如此)。在ServerThread中,从服务器获取可用客户端列表并循环访问它们并将消息发送给每个客户端。

答案 1 :(得分:0)

使用ObserverDesign模式保存您要向其发送消息的所有好友/用户的列表。使用HashMap维护所有观察者及其套接字的列表。收到消息后,您将检索每个用户的套接字并在每个套接字上写入相同的消息。