如何将 2 个 udp 客户端分组? [英] How to group 2 udp clients?

查看:34
本文介绍了如何将 2 个 udp 客户端分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是将 2 组客户分组并让他们相互交流.因此,如果连接了 2 个客户端,它们将只能相互通信,如果连接了第三个客户端,它将无法与其他 2 个客户端进行通信,但它会创建另一组 2 个客户端,依此类推......对现在,如果客户端发送一条消息,它会将其发送给所有客户端,但我不知道如何使其按上述方式工作.通过在控制台中输入一些内容从客户端发送消息.

What i'm trying to do is group 2 clients and make them communicate with eachother. So if 2 clients are connected they would only be able to communicate with eachother and if a third client got connected it would not be able to communicate with the 2 other clients but it would create another group of 2 clients and so on... Right now if a client sends a message it send it over to all clients but i don't know how to make it work like described above. Messages are send from client by typing something in console.

服务器:

public class Server extends Thread{

public final static int PORT = 7331;
private final static int BUFFER = 1024;

private DatagramSocket socket;
private ArrayList<InetAddress> clientAddresses;
private ArrayList<Integer> clientPorts;
private HashSet<String> existingClients;

public Server() throws IOException {
    socket = new DatagramSocket(PORT);
    System.out.println("[SERVER] UDP server successfully launched on port " + PORT);
    
    clientAddresses = new ArrayList<InetAddress>();
    clientPorts = new ArrayList<Integer>();
    existingClients = new HashSet<String>();
}

public void run() {
    byte[] buf = new byte[BUFFER];
    while (true) {
        try {
            //resets buffer so only new messages get displayed
            Arrays.fill(buf, (byte) 0);
            
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);

            String content = new String(buf, buf.length);

            InetAddress clientAddress = packet.getAddress();
            int clientPort = packet.getPort();

            String id = clientAddress.toString() + "," + clientPort;
            if (!existingClients.contains(id)) {
                existingClients.add(id);
                clientPorts.add(clientPort);
                clientAddresses.add(clientAddress);
            }

            System.out.println(id + " : " + content);
            byte[] data = (id + " : " + content).getBytes();
            for (int i = 0; i < clientAddresses.size(); i++) {
                InetAddress cl = clientAddresses.get(i);
                int cp = clientPorts.get(i);
                packet = new DatagramPacket(data, data.length, cl, cp);
                socket.send(packet);
            }
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

public static void main(String args[]) throws Exception {
    Server s = new Server();
    s.start();
}
}

客户:

public class Client implements Runnable {

public static void main(String args[]) throws Exception {
    String host = "127.0.0.1";

    DatagramSocket socket = new DatagramSocket();
    
    //handles the receiving part for every client (incoming packets to clients)
    MessageReceiver r = new MessageReceiver(socket);
    
    Client s = new Client(socket, host);
    Thread rt = new Thread(r);
    Thread st = new Thread(s);
    rt.start();
    st.start();
}



public final static int PORT = 7331;
private DatagramSocket sock;
private String hostname;

Client(DatagramSocket s, String h) {
    sock = s;
    hostname = h;
}

//sending clients socket to server
private void sendMessage(String s) throws Exception {
    //getting bytes from message
    byte buf[] = s.getBytes();
    
    //getting hostname from server
    InetAddress address = InetAddress.getByName(hostname);
    
    //setting up packet
    DatagramPacket packet = new DatagramPacket(buf, buf.length, address, PORT);
    
    //sending packet to server
    sock.send(packet);
}

public void run() {
    //connected boolean is used to send a greetings message once for every new client that has joined
    boolean connected = false;
    
    do {
        try {
            sendMessage("GREETINGS");
            connected = true;
        } catch (Exception e) {

        }
    } while (!connected);
    
    //reads from the console
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    
    while (true) {
        try {
            while (!in.ready()) {
                Thread.sleep(100);
            }
            
            //sends message from console to server
            sendMessage(in.readLine());
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}
}

//this class handles receiving part of clients
class MessageReceiver implements Runnable {
DatagramSocket sock;
byte buf[];

MessageReceiver(DatagramSocket s) {
    sock = s;
    buf = new byte[1024];
}

public void run() {
    while (true) {
        try {
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            sock.receive(packet);
            String received = new String(packet.getData(), 0, 
            packet.getLength());
            System.out.println(received);
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}
}

推荐答案

您正在尝试的是消息广播或消息转发器客户端.广播是在网络层实现的(使用广播本地网络广播地址).

What youre trying is a message broadcast or a message-repeater-client. broadcasting is implemented on network layer (using brodcast the local network broadcast adress).

如果您以这种方式实施它,当您有 2 个以上的客户端时,您的网络就会泛滥.向您的网络管理员致以最诚挚的问候.;-)

And if you implementing it that way, you'll flood your network, when you have more than 2 clients. Best regards to your network admin. ;-)

这篇关于如何将 2 个 udp 客户端分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆