Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package chat.client;
- import java.io.IOException;
- import java.net.*;
- import java.util.Arrays;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.swing.SwingUtilities;
- /**
- * A client thread that listens for datagrams coming in from the server in the background.
- *
- * @author Andre Lashley (C0375032)
- */
- public class ClientThread extends Thread {
- protected ChatClient client;
- protected InetAddress group;
- public ClientThread(ChatClient client) {
- this.client = client;
- }
- public void run() {
- try {
- client.multicastSocket = new MulticastSocket(5577);
- } catch (IOException ex) {
- client.logIt("Unable to create multicast socket on port "
- + client.multicastPort);
- return;
- }
- client.logIt("Listening on port " + client.multicastPort);
- try {
- client.multicastSocket.joinGroup(InetAddress.getByName(client.multicastIP));
- System.out.println(client.multicastIP);
- } catch (IOException ex) {
- client.logIt("Unknown multicast host: " + client.multicastIP);
- return;
- }
- client.logIt("Ready to recieve on multicast IP "
- + client.multicastIP + ":" + client.multicastPort);
- byte[] b = new byte[1024];
- DatagramPacket dgram = new DatagramPacket(b, b.length);
- // keep listening for datagram packets from the server
- while (true) {
- try {
- client.multicastSocket.receive(dgram);
- String message = new String(dgram.getData(), 0, dgram.getLength()).trim();
- sendUpdate(message);
- // reset the length field
- dgram.setLength(b.length);
- } catch (IOException ex) {
- client.logIt("Unable to recieve datagram");
- }
- }
- }
- private void sendUpdate(final String message) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- client.logIt(message);
- }
- });
- }
- }
Add Comment
Please, Sign In to add comment