Advertisement
Guest User

Untitled

a guest
Aug 19th, 2014
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. import java.net.*;
  2. import java.io.*;
  3.  
  4. public class MyGroupAPI
  5. {
  6. int port;
  7. InetAddress inet;
  8. MulticastSocket socket;
  9.  
  10. public MyGroupAPI(int port) throws Exception
  11. {
  12. this.port = port;
  13. socket = new MulticastSocket(port);
  14.  
  15. }
  16.  
  17. public void joinGroup(String address) throws Exception
  18. {
  19. inet = InetAddress.getByName(address);
  20. socket.joinGroup(inet);
  21.  
  22. }
  23.  
  24. public void sendMessage(String message) throws Exception
  25. {
  26. DatagramPacket dp = new DatagramPacket(message.getBytes(),message.length(),inet.port);
  27. socket.send(dp);
  28. }
  29.  
  30. public String receiveMessage() throws Exception
  31. {
  32. byte [] buff = new byte[1000];
  33. DatagramPacket dp = new DatagramPacket(buff,buff.length);
  34. socket.receive(dp);
  35. String msg = new String(buff);
  36. return dp.getSocketAddress()+":"+msg.trim();
  37. }
  38.  
  39. public static void main(String [] args) throws Exception
  40. {
  41. try{
  42. for(;;){
  43. MyGroupAPI ap = new MyGroupAPI(2020);
  44. ap.joinGroup("255.5.5.5");
  45. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  46. System.out.print("Message: ");
  47. String msg = br.readLine();
  48. ap.sendMessage(msg);
  49. System.out.println("Message received: ");
  50. System.out.println(ap.receiveMessage());
  51. }
  52. }
  53. catch(Exception e)
  54. {
  55. }
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement