Project

General

Profile

Statistics
| Revision:

root / proj / src / Channel.java @ 2

History | View | Annotate | Download (1.6 KB)

1
import java.io.IOException;
2
import java.net.DatagramPacket;
3
import java.net.InetAddress;
4
import java.net.MulticastSocket;
5
import java.net.UnknownHostException;
6

    
7
public class Channel implements Runnable{
8

    
9
        protected MulticastSocket socket = null;
10
    protected byte[] buf = new byte[64000];
11
    private String IP;
12
    private int Port;
13
    private Peer peer;
14
 
15
    public Channel(String mcIP,int mcPort, Peer peer) {
16
            this.IP = mcIP;
17
            this.Port = mcPort;
18
            this.peer = peer;
19
    }
20
    public void run() {
21
        
22
            try{
23
                    this.socket = new MulticastSocket(this.Port);
24
        InetAddress group = InetAddress.getByName(this.IP);
25
        this.socket.joinGroup(group);
26
        while (true) {
27
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
28
            this.socket.receive(packet);
29
           
30
            
31
            new Thread(new MessageParser(packet, peer)).start();
32
            String received = new String(
33
              packet.getData(), 0, packet.getLength());
34
            if ("end".equals(received)) {
35
                break;
36
            }
37
        }
38
        this.socket.leaveGroup(group);
39
        this.socket.close();
40
    }
41
            catch(IOException ex) {
42
                    System.out.println("Channel Exception:" + ex.toString());
43
                    ex.printStackTrace();
44
                    }
45
            }
46
    
47

    
48
        public void sendMessage(byte[] msg) throws UnknownHostException {
49

    
50
                        
51
                DatagramPacket packet = new DatagramPacket(msg, msg.length, InetAddress.getByName(this.IP), this.Port);
52

    
53
                try {
54
                    this.socket.send(packet);
55
                } catch (IOException e) {
56
                        e.printStackTrace();
57
                }
58
        }
59

    
60
}