Guest User

Untitled

a guest
Oct 18th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package chat.client;
  6.  
  7. import java.io.IOException;
  8. import java.net.*;
  9. import java.util.Arrays;
  10. import java.util.logging.Level;
  11. import java.util.logging.Logger;
  12. import javax.swing.SwingUtilities;
  13.  
  14. /**
  15. * A client thread that listens for datagrams coming in from the server in the background.
  16. *
  17. * @author Andre Lashley (C0375032)
  18. */
  19. public class ClientThread extends Thread {
  20.  
  21. protected ChatClient client;
  22. protected InetAddress group;
  23.  
  24. public ClientThread(ChatClient client) {
  25. this.client = client;
  26. }
  27.  
  28. public void run() {
  29. try {
  30. client.multicastSocket = new MulticastSocket(5577);
  31. } catch (IOException ex) {
  32. client.logIt("Unable to create multicast socket on port "
  33. + client.multicastPort);
  34. return;
  35. }
  36. client.logIt("Listening on port " + client.multicastPort);
  37.  
  38. try {
  39. client.multicastSocket.joinGroup(InetAddress.getByName(client.multicastIP));
  40. System.out.println(client.multicastIP);
  41. } catch (IOException ex) {
  42. client.logIt("Unknown multicast host: " + client.multicastIP);
  43. return;
  44. }
  45.  
  46. client.logIt("Ready to recieve on multicast IP "
  47. + client.multicastIP + ":" + client.multicastPort);
  48.  
  49. byte[] b = new byte[1024];
  50. DatagramPacket dgram = new DatagramPacket(b, b.length);
  51.  
  52. // keep listening for datagram packets from the server
  53. while (true) {
  54. try {
  55. client.multicastSocket.receive(dgram);
  56.  
  57. String message = new String(dgram.getData(), 0, dgram.getLength()).trim();
  58.  
  59. sendUpdate(message);
  60.  
  61. // reset the length field
  62. dgram.setLength(b.length);
  63. } catch (IOException ex) {
  64. client.logIt("Unable to recieve datagram");
  65. }
  66. }
  67.  
  68. }
  69.  
  70. private void sendUpdate(final String message) {
  71.  
  72. SwingUtilities.invokeLater(new Runnable() {
  73.  
  74. public void run() {
  75. client.logIt(message);
  76. }
  77. });
  78.  
  79. }
  80. }
Add Comment
Please, Sign In to add comment