簡體   English   中英

如何將 2 個 udp 客戶端分組?

[英]How to group 2 udp clients?

我正在嘗試做的是第 2 組客戶並使他們相互交流。 因此,如果連接了 2 個客戶端,它們將只能相互通信,如果連接了第三個客戶端,它將無法與其他 2 個客戶端進行通信,但它會創建另一組 2 個客戶端,依此類推......對現在,如果客戶端發送一條消息,它會將其發送給所有客戶端,但我不知道如何使其按上述方式工作。 通過在控制台中鍵入一些內容從客戶端發送消息。

服務器:

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);
        }
    }
}
}

您正在嘗試的是消息廣播或消息轉發器客戶端。 廣播是在網絡層實現的(使用廣播本地網絡廣播地址)。

如果您以這種方式實施它,當您有 2 個以上的客戶端時,您的網絡就會泛濫。 向您的網絡管理員致以最誠摯的問候。 ;-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM