Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.net.*;
- import java.io.*;
- public class MyGroupAPI
- {
- int port;
- InetAddress inet;
- MulticastSocket socket;
- public MyGroupAPI(int port) throws Exception
- {
- this.port = port;
- socket = new MulticastSocket(port);
- }
- public void joinGroup(String address) throws Exception
- {
- inet = InetAddress.getByName(address);
- socket.joinGroup(inet);
- }
- public void sendMessage(String message) throws Exception
- {
- DatagramPacket dp = new DatagramPacket(message.getBytes(),message.length(),inet.port);
- socket.send(dp);
- }
- public String receiveMessage() throws Exception
- {
- byte [] buff = new byte[1000];
- DatagramPacket dp = new DatagramPacket(buff,buff.length);
- socket.receive(dp);
- String msg = new String(buff);
- return dp.getSocketAddress()+":"+msg.trim();
- }
- public static void main(String [] args) throws Exception
- {
- try{
- for(;;){
- MyGroupAPI ap = new MyGroupAPI(2020);
- ap.joinGroup("255.5.5.5");
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- System.out.print("Message: ");
- String msg = br.readLine();
- ap.sendMessage(msg);
- System.out.println("Message received: ");
- System.out.println(ap.receiveMessage());
- }
- }
- catch(Exception e)
- {
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement