用JAVA将UDP服务器连接到客户端
我在一个文件上有一个服务器和一个客户端(比如client1),它们都工作得很好。我有这样一种情况:我有另一个客户端(比如client2)向服务器发送信息。此服务器必须将从client2获取的信息发送到client1。但是,当我尝试从client2发送信息时,在服务器和client1上使用相同的端口号和相同的IP地址时,client1一次也会接受 如何从client2发送信息,以便第一台服务器首先接受信息,然后将该信息发送到client1 客户端2代码: 我的服务器和客户端代码: 客户端1代码: 主程序用JAVA将UDP服务器连接到客户端,java,Java,我在一个文件上有一个服务器和一个客户端(比如client1),它们都工作得很好。我有这样一种情况:我有另一个客户端(比如client2)向服务器发送信息。此服务器必须将从client2获取的信息发送到client1。但是,当我尝试从client2发送信息时,在服务器和client1上使用相同的端口号和相同的IP地址时,client1一次也会接受 如何从client2发送信息,以便第一台服务器首先接受信息,然后将该信息发送到client1 客户端2代码: 我的服务器和客户端代码: 客户端1代码:
因为您正在使用
多播套接字
链接Client1
服务器
Client2
。如果服务器发送消息,每个客户端都会收到它,这是来自
当向多播组发送消息时,该主机和端口的所有订阅收件人都会收到该消息
如果您不想这样做,您可能需要使用两个不同的套接字,使用两个端口
- 端口1:
Client1
Server
- 端口2:
Client2
Server
import java.io.*;
import java.net.*;
class Client1
{
public static void main(String[] args)throws Exception {
try {
InetAddress ip=InetAddress.getByName("228.5.6.7");
int port=4270;
MulticastSocket sock=new MulticastSocket();
String msg="Hello All";
DatagramPacket packet;
while(true)
{
packet =new DatagramPacket(msg.getBytes(),msg.length(),ip,port);
sock.send(packet);
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Server implements Runnable
{
public void run()
{
try
{
//get the multicast ip
InetAddress ip = InetAddress.getByName("228.5.6.7");
int port=4270;
byte[] buffer=new byte[100];
byte[] data = null;
MulticastSocket sock=new MulticastSocket(port);
//join the multicast group
sock.joinGroup(ip);
while(true)
{
//create a datagram packet in which u will receive the msg
Thread.sleep(2000);
DatagramPacket pack=new DatagramPacket(buffer,buffer.length);
sock.receive(pack);
String msg = new String(buffer);
System.out.println("Sever Has Received :" +msg);
//SENDING THE MESSAGE TO CLIENT
System.out.println("Sending the Message!!!");
data = msg.getBytes();
DatagramPacket pack1 = new DatagramPacket(data,msg.length(),ip,port);
Thread.sleep(2000);
sock.send(pack1);
}
}
catch (Exception ex) {
Thread t = Thread.currentThread();
t.getUncaughtExceptionHandler().uncaughtException(t, ex);
}
}
}
class Client implements Runnable
{
public void run()
{
try {
InetAddress address1 = InetAddress.getByName("228.5.6.7");
int port=4271;
MulticastSocket socket1 = new MulticastSocket(port);
//join a Multicast group and send the group salutations
socket1.joinGroup(address1);
byte[] data1 = new byte[256];
DatagramPacket packet1 = new DatagramPacket(data1,data1.length);
while(true)
{
// receive the packets
socket1.receive(packet1);
String str = new String(packet1.getData(),0,packet1.getLength());
Thread.sleep(2000);
System.out.println("Client Received : "+str);
}
}
catch (Exception ex) {
Thread t = Thread.currentThread();
t.getUncaughtExceptionHandler().uncaughtException(t, ex);
}
}
}
class ClientAndServer
{
public static void main(String[] args)
{
Server s = new Server();
//First start Server and then Start client
Thread t1 = new Thread(s);
t1.start();
Client c = new Client();
Thread t2 = new Thread(c);
t2.start();
}
}