我如何接收数据

时间:2019-06-17 05:21:27

标签: java udp

我的听众->

    public void startListening(){
        String[] details = session.split(":");
        SessionUser user = new SessionUser();
        System.out.println("Waiting for another user..");
        listening = new Thread("listen thread"){
            public void run() {
                while(true) {
                    while (user.users < 2) {
                        try {
                            Socket socket1 = socket.accept();
                            System.out.println(socket1.getInetAddress().toString() + " has joined...");
                            user.users++;
                            socket1.close();
                        } catch (Exception e) {
                            System.out.println("Ran into a error!");
                        }
                    }
                }
            }
        };
        listening.start();

    }

我的发件人->

    public void join(InetAddress address, int port){
        byte[] data = new byte[1024];
        DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
        try {
            DatagramSocket socket = new DatagramSocket();
            System.out.println("Attempting to join session <" + address.toString() + ":" + port + ">!");
            socket.send(packet);
            System.out.println("Joining......");
        }catch (Exception e){
            System.out.println("Unable to connect, this may be a server error, or you've entered incorrect details!");
        }
    }

所以我只想在连接时将数据包发送到主机服务器,但是,当我运行此程序时,我看不到任何输出,这里的图片可能会更好地解释它-> {{3 }}

2 个答案:

答案 0 :(得分:1)

在接收方中,您正在从TCP套接字读取数据,而发送方正在发送UDP数据包。这行不通。

答案 1 :(得分:1)

更改服务器以同时接收数据包

DatagramSocket serverSocket = new DatagramSocket(port);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(packet); // This will block until a packet is received
System.out.println("Received: " + new String(packet.getData()));

尝试与客户进行测试

public void join(InetAddress address, int port){
        byte[] data = "Hello".getBytes();
        DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
        try {
            DatagramSocket socket = new DatagramSocket();
            System.out.println("Attempting to join session <" + address.toString() + ":" + port + ">!");
            socket.send(packet);
            System.out.println("Joining......");
        }catch (Exception e){
            System.out.println("Unable to connect, this may be a server error, or you've entered incorrect details!");
        }
}

如果需要维护连接,最好将TCP与套接字一起使用。