1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| public final class NetworkManager {
DatagramChannel channel = null;
private final static int BUFFER_SIZE = 1024;
protected Selector selector;
InetSocketAddress isa ;
/**
* Create a network manager with any port allocated by the OS.
*/
public NetworkManager() {
this.isa = new InetSocketAddress(0);
}
public NetworkManager(InetSocketAddress isa) {
this.isa = isa;
}
protected void initChannel() throws IOException
{
// Prepare the channel.
channel = DatagramChannel.open();
channel.configureBlocking(false);
// Connect udp channel.
channel.bind(new InetSocketAddress(isa.getPort()));
// Prepare the selector.
selector = Selector.open();
int interestSet = SelectionKey.OP_READ;
channel.register(selector, interestSet);
}
public void send(DatagramPacket sendMessage) throws IOException {
if (channel == null) {
initChannel();
}
ByteBuffer bb = ByteBuffer.wrap(sendMessage.getData());
channel.send(bb, sendMessage.getSocketAddress());
}
private RawMessage read(SelectionKey key) throws IOException {
DatagramChannel chan = (DatagramChannel) key.channel();
ByteBuffer readBuffer = ByteBuffer.allocate(BUFFER_SIZE);
// Exception se produit ici !!
chan.read(readBuffer);
RawMessage rawMessage = getRawMessage(chan.getRemoteAddress(), readBuffer);
return rawMessage;
}
/**
* Wait until a message comming. Blocked method.
*
* @return A raw message from the channel or null if wake up.
* @throws IOException
*/
public RawMessage receive() throws IOException {
if (channel == null) {
initChannel();
}
selector.select();
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> itSelectkey = selector.selectedKeys().iterator();
while (itSelectkey.hasNext()) {
SelectionKey key = itSelectkey.next();
if (key.isReadable())
{
return read(key);
}
}
return null;
}
/**
* Wake up the selector, selector is used in receive() method who is
* blocking.
*/
public void wakeUp() {
selector.wakeup();
} |