- 论坛徽章:
- 0
|
服务器端:
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public
class Server
{
public static void main(String [] arstring)
{
try
{
System.out.println("im the server");
MulticastSocket multicastSocket = new MulticastSocket(7777);
InetAddress inetAddress = InetAddress.getByName("230.0.0.1");
multicastSocket.joinGroup(inetAddress);
while (true)
{
byte [] arb = new byte [1000];
DatagramPacket datagramPacket = new DatagramPacket(arb, arb.length);
multicastSocket.receive(datagramPacket);
System.out.println(new String(arb));
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
}
客户端
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public
class Client
{
public static void main(String [] arstring)
{System.out.println("im the client..");
try
{
byte [] arb = new byte [] {'h','e','l','l','o'};
InetAddress inetAddress = InetAddress.getByName("230.0.0.1");
DatagramPacket datagramPacket = new DatagramPacket(arb, arb.length, inetAddress, 7777);
MulticastSocket multicastSocket = new MulticastSocket();
multicastSocket.joinGroup(inetAddress);
multicastSocket.send(datagramPacket);
System.out.println("send ok");
multicastSocket.close();
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
} |
|