简体   繁体   English

Java广播和侦听在同一端口上

[英]Java Broadcasting and listening on same port

How can broadcast a message from single server to multiple clients and listen for a reply from one of the clients. 如何将消息从单个服务器广播到多个客户端,以及如何侦听客户端之一的回复。

I used Multicast Programming to broadcast the message to the clients. 我使用多播编程将消息广播到客户端。 And If i send the message from one of my clients back to the server either through TCP or UDP, I am getting a " java.net.ConnectException: Connection refused: connect " exception. 而且,如果我通过TCP或UDP将消息从客户端之一发送回服务器,则会收到“ java.net.ConnectException:连接被拒绝:connect ”异常。

Please help me out. 请帮帮我。

Thanks in Advance. 提前致谢。

Sender Code : 发件人代码:

// Broadcasting the message //广播消息

    msg = "This is multicast! " + counter;
                counter++;
                outBuf = msg.getBytes();

                // Send to multicast IP address and port
                InetAddress address = InetAddress.getByName("224.2.2.3");
                outPacket = new DatagramPacket(outBuf, outBuf.length, address,
                        PORT);

                socket.send(outPacket);

                System.out.println("Server sends : " + msg);

                socket.close();



                // Receiving TCP
                apSock = new Socket("131.151.88.165", 6161);
                apBuffReader = new BufferedReader(new InputStreamReader(
                        apSock.getInputStream()));
                while ((ap2Toap1 = apBuffReader.readLine()) != null) {
                    System.out.println(ap2Toap1);
                }

Receiver Code :

count++;
                inPacket = new DatagramPacket(inBuf, inBuf.length);
                socket.receive(inPacket);
                String msg = new String(inBuf, 0, inPacket.getLength());
                System.out.println("From " + inPacket.getAddress() + " Msg : "
                        + msg);

                socket.close();



                // Sending TCP
                apSock = new Socket("131.151.88.165", 6161);
                System.out.println("Hello2");
                respWriter = new PrintWriter(apSock.getOutputStream());
                System.out.println("Writing back to the server");
                respWriter.println(outBuf);
                if (respWriter != null)
                    respWriter.close();

There is no listening in your code. 您的代码中没有监听。 TCP listening in Java is accomplished via a ServerSocket. Java中的TCP侦听是通过ServerSocket完成的。 You aren't using one. 您没有使用一个。 Instead you're using Sockets at both ends. 相反,您在两端都使用套接字。 So what you have is two clients and no server. 因此,您只有两个客户端,没有服务器。 No communication is possible between two TCP clients. 两个TCP客户端之间无法进行通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM