如何在 Java 中将 UDP 与多个客户端一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13042215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:18:32  来源:igfitidea点击:

How to use UDP with multiple Clients in Java

javaudpdatagram

提问by David Sonnenfeld

I have the following Situation.

我有以下情况。

I have a Server class. I have a Client class. I have a MultiServerThread class.

我有一个服务器类。我有一个客户类。我有一个 MultiServerThread 类。

When a Client connects to a Server, the Server creates a new MultiServerThread, which is processing the Input from the Client. That way I can have multiple Clients. So far so good. The connection goes via TCP.

当客户端连接到服务器时,服务器会创建一个新的 MultiServerThread,它正在处理来自客户端的输入。这样我就可以有多个客户端。到现在为止还挺好。连接通过 TCP 进行。

A short example:

一个简短的例子:

Server class:

服务器类:

...
public static void main(String[] args) throws IOException {     
    ServerSocket serverSocket = null;
    boolean listening = true;


    try {
        serverSocket = new ServerSocket(9999);
    } catch (IOException e) {
      System.err.println("Could not listen on port: " +  serverSocket.getLocalPort() + ".");
        System.exit(-1);
    }

    while (listening) {
        new MultiServerThread(serverSocket.accept()).start();
    }
    serverSocket.close();
}
...

Client class:

客户端类:

...
public static void main(String[] args) throws IOException {

    socket = new Socket(hostname, port);
    out = new PrintWriter(socket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    stdIn = new BufferedReader(new InputStreamReader(System.in));
    String fromServer;
    String fromUser;

    while ((fromServer = in.readLine()) != null) {
        System.out.println("Server: " + fromServer);
        if (fromServer.equals("Bye.")) {
            break;
        }

        fromUser = stdIn.readLine();
        if (fromUser != null) {
            System.out.println("Client: " + fromUser);
            out.println(fromUser);
        }
    }

    out.close();
    in.close();
    stdIn.close();
    socket.close();
}
...

MultiServerThread class:

MultiServerThread 类:

...
public MultiServerThread(Socket socket) throws SocketException {
    super("MultiServerThread");
    this.socket = socket;
    //   dSocket = new DatagramSocket(4445);
}

public void run() {
    try {
        PrintWriter myOutput = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader myInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        myOutput.println("Connected to client and ready to accept commands.");

        while ((clientInput = myInput.readLine()) != null) {

            //A SIMPLE LOGIN A USER
            if (clientInput.contains("!login")) {

            //save some string given by client into loggedUser
            String loggedUser = clientInput.substring(7);

            }

        myOutput.close();
        myInput.close();
        socket.close();

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

What I need is:

我需要的是:

I need to implement a notification that comes from a Server when for example the Username is "Bob". If the username is "Bob", the server should give a notification to the Client "Bob is here again!". In my project/homework this should be done with datagrams in Java.

例如,当用户名是“Bob”时,我需要实现来自服务器的通知。如果用户名是“Bob”,服务器应该给客户端一个通知“Bob 又来了!”。在我的项目/作业中,这应该使用 Java 中的数据报来完成。

So if the clientinput is "!login bob" then a datagram packet with the message ("Bob is here again!") should be sent to the client.

因此,如果客户端输入是“!login bob”,则应将带有消息(“Bob 又来了!”)的数据报包发送到客户端。

Question: Where exactly should I put the code of the Datagram request in? Can I put the datagram packet request into the MultiServerThread or into the Client?

问题:我到底应该把数据报请求的代码放在哪里?我可以将数据报包请求放入 MultiServerThread 或 Client 中吗?

It would be easier in the MultiServerThread because it already handles the !login. Here:

在 MultiServerThread 中会更容易,因为它已经处理了 !login。这里:

     if (clientInput.contains("!login")) {
            //save some string given by client into loggedUser
            String loggedUser = clientInput.substring(7);

            //send datagram request to Server???

            }

But this is going against the principle of networking?

但这是否违背了联网原则?

采纳答案by David Sonnenfeld

I got it working ;-)

我让它工作了;-)

I definied a udp port in the thread and client class... the client class got his port with arguments... it gave the udp Port to the thread... so both had the udp ports ;)

我在线程和客户端类中定义了一个 udp 端口​​......客户端类通过参数获取了他的端口......它把 udp 端口​​提供给了线程......所以两者都有 udp 端口​​;)

回答by Steve's a D

you need to send the UDP port number to your client through the initial TCP connection. Then you start listening for UDP datagrams on your client on that port number. All other communications from server -> client will be on this udp socket. This is what your assignment suggests

您需要通过初始 TCP 连接将 UDP 端口号发送到您的客户端。然后您开始在您的客户端上在该端口号上侦听 UDP 数据报。来自服务器 -> 客户端的所有其他通信都将在此 udp 套接字上。这就是你的作业所建议的