receiver.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Arrays;
// Server side
public class receiver
{
public static void main(String[] args) throws IOException
{
InetAddress inetRemoteAddr = InetAddress.getByName("224.0.0.5");
DatagramPacket recvPack = new DatagramPacket(new byte[1024], 1024);
MulticastSocket server = new MulticastSocket(8888);
// you must join the multicast group ;
server.joinGroup(inetRemoteAddr);
System.out.println("---------------------------------");
System.out.println("Server current start......");
System.out.println("---------------------------------");
while (true)
{
server.receive(recvPack);
byte[] recvByte = Arrays.copyOfRange(recvPack.getData(), 0,
recvPack.getLength());
System.out.println("Server receive msg:" + new String(recvByte));
}
}
}
sender.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
// Client
public class sender
{
public static void main(String[] args) throws IOException
{
int port = 8888;
byte[] msg = "Connection successfully!!!".getBytes();
InetAddress inetRemoteAddr = InetAddress.getByName("224.0.0.5");
try ( // MulticastSocket
MulticastSocket client = new MulticastSocket()) {
DatagramPacket sendPack = new DatagramPacket(msg, msg.length,
inetRemoteAddr, port);
client.send(sendPack);
System.out.println("Client send msg complete");
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.