HƯỚNG DẪN How to extract Client IP/Name and Port from DatagramChannel

Joe

Thành viên VIP
21/1/13
3,065
1,342
113
hello.gif

From the two previous Postings (DatagramChannel with Selector and Client-Server with DatagramSocket and DatagramChannel) I have to showed you how to implement ONE DatagramChannel (and DatagramSocket) as a Client AND as a Server as well. The following Receiving or Listening thread:

DatagramChannel
Java:
  private class Receiver extends Thread {
    public Receiver(int port) {
      this.port = port;
    }
    private int port;
    public void run( ) {
      try {
        channel = DatagramChannel.open();
        channel.socket().bind(new InetSocketAddress(port));
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        // read the incoming GIF using ByteBuffer
        ByteBuffer buf = ByteBuffer.allocate(65535);
        while (!closed) {
          buf.clear();
          channel.receive(buf);
          buf.flip();
          ...// do something
          }
         }
       } catch (Exception e) { }        
    }
  }
DatagramSocket
Java:
  private class Listener extends Thread {
    public Listener(int port) {
      this.port = port;
    }
    protected int port;
    public void run( ) {
      try {
        byte bb[] = new byte[65535];
        DatagramPacket pkt = new DatagramPacket(bb, bb.length);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        listener = new DatagramSocket(port);
        // read the incoming GIF
        while (!closed) {
          listener.receive(pkt);
          bb = pkt.getData();
          ....// do something
        }
      } catch (Exception e) { }        
    }
  }
receives the data from a remote client which could be a DatagramSocket or DatagramChannel Client. By convention the received data always contain the InetSocketAddress of the sender. With the InetSocketAddress your app can act as a SERVER which then can spawn a new thread that communicates peer-to-peer with the remote client. The way how to extract the remote client IP/Port is as following:

DatagramSocket via DatagramPacket:
Java:
        byte bb[] = new byte[65535];
        DatagramPacket packet = new DatagramPacket(bb, bb.length);
        ...
        listener.receive(pkt);
        InetAddress clientIP = packet.getAddress();
        String clientHost = clientIP.getHostName();
        int clientPort = packet.getPort();
        ...
DatagramChannel:
Java:
        ByteBuffer buf = ByteBuffer.allocate(65535);
        InetSocketAddress clientIP = (InetSocketAddress)channel.receive(buf);
        String clientHost = clientIP.getHostName(); // either a name or the IP
        int clientPort = clientIP.getPort();
        ...