如何将消息从单个服务器广播到多个客户端,并侦听其中一个客户端的回复。
我使用多播编程将消息广播给客户端。如果我通过TCP或UDP将我的一个客户端的消息发送回服务器,我会收到“ java.net.ConnectException:Connection refused:connect ”异常。
请帮帮我。
先谢谢。
发件人代码:
//广播消息
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();
答案 0 :(得分:0)
您的代码中没有收听。 Java中的TCP侦听是通过ServerSocket完成的。你没有使用它。相反,你在两端使用套接字。所以你拥有的是两个客户端,没有服务器。两个TCP客户端之间无法进行通信。