Beispiel #1
1
  public static void main(String[] args) throws IOException, InterruptedException {
    boolean running = true;
    // udp protocol over a socket.
    DatagramSocket socket = new DatagramSocket();

    while (running) {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String line = br.readLine();
      String[] inputs = line.split(" ");

      if (inputs.length < 2) {
        System.out.println("Usage: username command id");
        socket.close();
        return;
      }

      byte[] byteArr = (inputs[0] + " " + inputs[1] + " " + inputs[2]).getBytes();

      // send request
      byte[] buf = new byte[256];
      InetAddress address = InetAddress.getByName("localhost");
      DatagramPacket packet = new DatagramPacket(byteArr, byteArr.length, address, 4445);
      socket.send(packet);

      // get response
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);

      // display response
      String received = new String(packet.getData(), 0, packet.getLength());
      System.out.println("From server: " + received);
    }
    //   socket.close();
  }
Beispiel #2
1
  public void run() {
    if (ServerSocket == null) return;
    while (true) {
      try {
        InetAddress address;
        int port;
        DatagramPacket packet;
        byte[] data = new byte[1460];
        packet = new DatagramPacket(data, data.length);
        ServerSocket.receive(packet);
        //
        //
        address = packet.getAddress();
        port = packet.getPort();
        System.out.println("get the Client port is: " + port);
        System.out.println("get the data length is: " + data.length);

        FileWriter fw = new FileWriter("Fortunes.txt");
        PrintWriter out = new PrintWriter(fw);
        for (int i = 0; i < data.length; i++) {
          out.print(data[i] + "  ");
        }
        out.close();
        System.out.println("Data has been writen to destination!");

        packet = new DatagramPacket(data, data.length, address, port);
        ServerSocket.send(packet);
        System.out.println("Respond has been made!");
      } catch (Exception e) {
        System.err.println("Exception: " + e);
        e.printStackTrace();
      }
    }
  }
  public MSSqlServerInfo(String host) throws SQLException {
    try {
      InetAddress addr = InetAddress.getByName(host);
      DatagramSocket socket = new DatagramSocket();
      byte[] msg = new byte[] {0x02};
      DatagramPacket p = new DatagramPacket(msg, msg.length, addr, 1434);

      socket.send(p);

      byte[] buf = new byte[4096];

      p = new DatagramPacket(buf, buf.length);
      socket.setSoTimeout(m_timeout);

      for (int i = 0; i < m_numRetries; i++) {
        try {
          socket.receive(p);
          String infoString = extractString(buf, p.getLength());
          m_serverInfoStrings = split(infoString, ';');

          return;
        } catch (InterruptedIOException toEx) {
        }
      }
    } catch (Exception e) {
      // Ignore...
    }

    throw new SQLException(Messages.get("error.msinfo.badinfo", host), "HY000");
  }
Beispiel #4
0
  // Check if the datagramsocket adaptor can send with a packet
  // that has not been initialized with an address; the legacy
  // datagram socket will send in this case
  private static void test2() throws Exception {
    DatagramChannel sndChannel = DatagramChannel.open();
    sndChannel.socket().bind(null);
    InetSocketAddress sender =
        new InetSocketAddress(InetAddress.getLocalHost(), sndChannel.socket().getLocalPort());

    DatagramChannel rcvChannel = DatagramChannel.open();
    rcvChannel.socket().bind(null);
    InetSocketAddress receiver =
        new InetSocketAddress(InetAddress.getLocalHost(), rcvChannel.socket().getLocalPort());

    rcvChannel.connect(sender);
    sndChannel.connect(receiver);

    byte b[] = "hello".getBytes("UTF-8");
    DatagramPacket pkt = new DatagramPacket(b, b.length);
    sndChannel.socket().send(pkt);

    ByteBuffer bb = ByteBuffer.allocate(256);
    rcvChannel.receive(bb);
    bb.flip();
    CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
    if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed");

    // Check that the pkt got set with the target address;
    // This is legacy behavior
    if (!pkt.getSocketAddress().equals(receiver)) throw new RuntimeException("Test failed");

    rcvChannel.close();
    sndChannel.close();
  }
Beispiel #5
0
 /** Receive loop for private messaqes. Can be stopped with {@link #setRunning(boolean)} */
 private void receivePrivateMessages() {
   while (isRunning()) {
     try {
       final byte[] buf = new byte[BUFFER_SIZE];
       final DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
       if (LOG.isDebugEnabled()) {
         LOG.debug(
             "Waiting for private message, listening on port " + privateSocket.getLocalPort());
       }
       privateSocket.receive(receivePacket); // wait for a packet
       final String data = toString(receivePacket);
       if (LOG.isDebugEnabled()) {
         LOG.debug("Got a private message: " + data);
       }
       if (LOG.isDebugEnabled()) {
         LOG.debug(
             "Received "
                 + data
                 + " from "
                 + receivePacket.getAddress()
                 + ":"
                 + receivePacket.getPort()
                 + ".");
       }
       processPrivateMessage(data);
     } catch (IOException e) {
       LOG.error(BUNDLE_MARKER, e.toString(), e);
     }
   }
   if (LOG.isDebugEnabled()) {
     LOG.debug("Stopped listening to private messages.");
   }
 }
    public void run() {
      active = true;

      byte[] b = new byte[PACKET_LENGTH];
      DatagramPacket p = new DatagramPacket(b, b.length);

      while (active) {
        try {
          socket.receive(p);

          // this string constructor which accepts a charset throws an exception if it is
          // null
          if (encoding == null) {
            handlerThread.append(new String(p.getData(), 0, p.getLength()));
          } else {
            handlerThread.append(new String(p.getData(), 0, p.getLength(), encoding));
          }
        } catch (SocketException se) {
          // disconnected
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }
      }

      getLogger().debug("{}'s thread is ending.", MulticastReceiver.this.getName());
    }
Beispiel #7
0
  public void run() {

    while (true) {

      DatagramPacket msg = new DatagramPacket(new byte[1000], 1000);

      try {

        socket.receive(msg);

      } catch (IOException e) {

      }
      ;

      String container = new String(msg.getData());

      container = container.trim();

      if (container.substring(0, container.indexOf(' ')).equals("vfd"))
        CALM.box.mailAction(container.substring(container.indexOf(' ') + 1, container.length()));
      else if (container.substring(0, container.indexOf(' ')).equals("dfv"))
        CALM.box.mailAction2(container.substring(container.indexOf(' ') + 1, container.length()));
    }
  }
  private void listen() throws Exception {
    System.out.println("Listening on port: " + serverPort);
    // Initialize socket
    socket = new DatagramSocket(serverPort);

    // While running
    while (run) {

      // Wait for handshake
      packet = new DatagramPacket(response, response.length);
      socket.receive(packet); // Blocking
      // System.out.println("RT: got packet");
      Packet p = new Packet(packet.getData());

      if (p.isHandshake()) {
        // System.out.println("RT: is handshake");
        // Get client connection info
        InetAddress IPAddress = packet.getAddress();
        int port = packet.getPort();

        // Process handshake
        processHandshake(p, IPAddress, port);

        // Get message
        MyMessage message = getMessage();

        if (message != null) {
          rc.rreceive(message);
        }
      }
    }
  }
  public void run() {
    System.out.println("ExeUDPServer开始监听..." + UDP_PORT);
    DatagramSocket ds = null;
    try {
      ds = new DatagramSocket(UDP_PORT);
    } catch (BindException e) {
      System.out.println("UDP端口使用中...请重关闭程序启服务器");
    } catch (SocketException e) {
      e.printStackTrace();
    }

    while (ds != null) {
      DatagramPacket dp = new DatagramPacket(buf, buf.length);
      try {
        ds.receive(dp);
        // 得到把该数据包发来的端口和Ip
        int rport = dp.getPort();
        InetAddress addr = dp.getAddress();
        String recvStr = new String(dp.getData(), 0, dp.getLength());
        System.out.println("Server receive:" + recvStr + " from " + addr + "  " + rport);

        // 给客户端回应
        String sendStr = "echo of " + recvStr;
        byte[] sendBuf;
        sendBuf = sendStr.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, rport);
        ds.send(sendPacket);

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Beispiel #10
0
  public static void main(final String... args) throws Throwable {
    final String remotehost = args[0];
    final int remoteport = Integer.parseInt(args[1]);
    final DatagramSocket socket = new DatagramSocket();

    final byte buffer[] = new byte[512];

    final InetSocketAddress remote = new InetSocketAddress(remotehost, remoteport);

    buffer[0] = ENQUIRY;
    buffer[1] = END_OF_TRANSMISSION;
    socket.send(new DatagramPacket(buffer, 2, remote));

    final DatagramPacket p = new DatagramPacket(buffer, buffer.length);
    socket.receive(p);

    if ((p.getLength() == 2) && (buffer[0] == ACKNOWLEDGE) && (buffer[1] == END_OF_TRANSMISSION))
      System.out.println("Connection established");
    else {
      System.out.println("Connection failed");
      return;
    }

    for (; ; ) {
      int ptr = 0;
      for (int d; (d = System.in.read()) != '\n'; ) buffer[ptr++] = (byte) d;

      socket.send(new DatagramPacket(buffer, ptr, remote));
    }
  }
  public void run() {
    while (true) {
      try {
        DatagramSocket ClientSoc = new DatagramSocket(ClinetPortNumber);
        String Command = "GET";

        byte Sendbuff[] = new byte[1024];
        Sendbuff = Command.getBytes();

        InetAddress ServerHost = InetAddress.getLocalHost();
        ClientSoc.send(new DatagramPacket(Sendbuff, Sendbuff.length, ServerHost, 5217));

        byte Receivebuff[] = new byte[1024];
        DatagramPacket dp = new DatagramPacket(Receivebuff, Receivebuff.length);
        ClientSoc.receive(dp);

        NewsMsg = new String(dp.getData(), 0, dp.getLength());
        System.out.println(NewsMsg);
        lblNewsHeadline.setText(NewsMsg);

        Thread.sleep(5000);
        ClientSoc.close();
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
  public void run() {

    while (moreQuotes) {
      try {
        byte[] buf = new byte[256];

        // receive request
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet); // containing IP ecc.

        // figure out response
        String dString = null;
        if (in == null) dString = new Date().toString();
        else dString = getNextQuote();
        buf = dString.getBytes();

        // send the response to the client at "address" and "port"
        InetAddress address = packet.getAddress();
        int port = packet.getPort();
        packet = new DatagramPacket(buf, buf.length, address, port);
        socket.send(packet);
      } catch (IOException e) {
        e.printStackTrace();
        moreQuotes = false;
      }
    }
    socket.close();
  }
  public static void main(String args[]) {
    DatagramSocket skt = null;
    try {
      skt = new DatagramSocket(6789);
      byte[] buffer = new byte[1000];
      while (true) {
        DatagramPacket request = new DatagramPacket(buffer, buffer.length);
        skt.receive(request);
        System.out.println("Data received from client");
        System.out.println(new String(request.getData()));
        Thread.sleep(15000);

        String[] arrayMsg = (new String(request.getData())).split(" ");

        System.out.println(arrayMsg[0] + "server processed");

        byte[] sendMsg = (arrayMsg[0] + "server processed").getBytes();

        DatagramPacket reply =
            new DatagramPacket(sendMsg, sendMsg.length, request.getAddress(), request.getPort());

        System.out.println("sending data from server to client");
        Thread.sleep(15000);
        ;
        skt.send(reply);
      }
    } catch (Exception e) {

    }
  }
  /**
   * Attempts to log a client in using the authentication server. Authentication server needs to run
   * on the same host as the file server.
   *
   * @throws IOException Error reading from socket.
   */
  private void login() throws IOException {
    // set up required variables
    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress authServerIP =
        InetAddress
            .getLocalHost(); // because authentication server runs on same host as file server
    byte[] dataToSend;
    byte[] receivedData = new byte[BUFFER_SIZE];

    // get username and password
    String userName = inFromClient.readLine().trim(); // get username
    String password = inFromClient.readLine().trim(); // get password
    dataToSend = new String(userName + " " + password).getBytes();

    // send the username and password for processing by authentication server
    DatagramPacket packetToSend =
        new DatagramPacket(dataToSend, dataToSend.length, authServerIP, AUTHENTICATION_PORT);
    clientSocket.send(packetToSend);

    // receive the response from the authentication server
    DatagramPacket receivedPacket = new DatagramPacket(receivedData, receivedData.length);
    clientSocket.receive(receivedPacket);
    String receivedString = new String(receivedPacket.getData()).trim();
    receivedData = receivedString.getBytes();
    if (receivedString.equals("yes")) {
      outToClient.writeBytes(receivedString); // successful login
    } else {
      outToClient.writeBytes("no"); // unsuccessful login
    }
  }
  private String receiveDataUdp(InetSocketAddress clientAddress) throws IOException, JSONException {
    EmployeeList employees = new EmployeeList();
    DatagramSocket datagramServer = new DatagramSocket(clientAddress);
    byte dataFromServer[] = new byte[2048];
    boolean isTimeExpired = false;
    datagramServer.setSoTimeout((int) SECONDS.toMillis(PROTOCOL_GROUP_TIMEOUT - 5));

    System.out.println(
        "[INFO] -----------------------------------------\n"
            + "[INFO] Collecting information from nodes....");
    while (!isTimeExpired) {
      DatagramPacket datagramPacketacket =
          new DatagramPacket(dataFromServer, dataFromServer.length);
      try {
        datagramServer.receive(datagramPacketacket);
      } catch (SocketTimeoutException e) {
        System.out.println(
            "[WARNING] -----------------------------------------\n"
                + "[WARNING] Waiting time expired...");
        isTimeExpired = true;
        continue;
      }
      String receivedJson = (String) deserialize(datagramPacketacket.getData());
      System.out.println("[INFO] " + "Received employee in JSON: " + receivedJson);
      employees.add(jsonToEmployee(receivedJson));
    }
    datagramServer.close();
    return employeeToXml(employees);
  }
Beispiel #16
0
  public void send(byte[] buf, DatagramPacket dp) throws InterruptedException, IOException {
    StringBuilder source = new StringBuilder();
    source.append(dp.getAddress());
    String dataType = type;
    byte[] trimmedBuf = Arrays.copyOf(buf, dp.getLength());
    String rawPRI = new String(trimmedBuf, 1, 4, Charset.forName("UTF-8"));
    int i = rawPRI.indexOf(">");
    if (i <= 3 && i > -1) {
      String priorityStr = rawPRI.substring(0, i);
      int priority = 0;
      int facility = 0;
      try {
        priority = Integer.parseInt(priorityStr);
        facility = (priority >> 3) << 3;
        facility = facility / 8;
        dataType = facilityMap.get(facility);
      } catch (NumberFormatException nfe) {
        log.warn("Unsupported format detected by SyslogAdaptor:" + Arrays.toString(trimmedBuf));
      }
    }

    bytesReceived += trimmedBuf.length;
    Chunk c =
        new ChunkImpl(dataType, source.toString(), bytesReceived, trimmedBuf, SyslogAdaptor.this);
    dest.add(c);
  }
Beispiel #17
0
  public void run() {
    final byte[] receive_buf = new byte[65535];
    DatagramPacket packet = new DatagramPacket(receive_buf, receive_buf.length);
    byte[] data;
    ByteArrayInputStream inp_stream;
    DataInputStream inp = null;
    Message msg;

    while (mcast_sock != null && receiver != null && Thread.currentThread().equals(receiver)) {
      packet.setData(receive_buf, 0, receive_buf.length);
      try {
        mcast_sock.receive(packet);
        data = packet.getData();
        inp_stream = new ExposedByteArrayInputStream(data, 0, data.length);
        inp = new DataInputStream(inp_stream);
        msg = new Message();
        msg.readFrom(inp);
        up(new Event(Event.MSG, msg));
      } catch (SocketException socketEx) {
        break;
      } catch (Throwable ex) {
        log.error("failed receiving packet (from " + packet.getSocketAddress() + ")", ex);
      } finally {
        Util.close(inp);
      }
    }
    if (log.isTraceEnabled()) log.trace("receiver thread terminated");
  }
Beispiel #18
0
  public static void main(String args[]) throws Exception {

    String serverHostname = args[0];
    int portNumber = Integer.parseInt(args[1]);

    try {
      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

      DatagramSocket clientSocket = new DatagramSocket();

      InetAddress IPAddress = InetAddress.getByName(serverHostname);
      System.out.println("Attempting to connect to " + IPAddress + ") via UDP port " + portNumber);
      System.out.println("Enter \"Quit\" to exit program");

      while (true) {
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];

        System.out.print("Enter Message: ");
        String sentence = inFromUser.readLine();

        if (sentence.equals("Quit")) break;

        sendData = sentence.getBytes();

        System.out.println("Sending data to " + sendData.length + " bytes to server.");
        DatagramPacket sendPacket =
            new DatagramPacket(sendData, sendData.length, IPAddress, portNumber);

        clientSocket.send(sendPacket);

        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

        System.out.println("Waiting for return packet");
        clientSocket.setSoTimeout(10000);

        try {
          clientSocket.receive(receivePacket);
          String modifiedSentence = new String(receivePacket.getData());

          InetAddress returnIPAddress = receivePacket.getAddress();

          int port = receivePacket.getPort();

          System.out.println("From server at: " + returnIPAddress + ":" + port);
          System.out.println("Message: " + modifiedSentence);
        } catch (SocketTimeoutException ste) {
          System.out.println("Timeout Occurred: Packet assumed lost");
        }
        System.out.print("\n");
      }

      clientSocket.close();
    } catch (UnknownHostException ex) {
      System.err.println(ex);
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
  /**
   * Initializes a new <tt>DatagramPacket</tt> instance which is a clone of a specific
   * <tt>DatagramPacket</tt> i.e. the properties of the clone <tt>DatagramPacket</tt> are clones of
   * the specified <tt>DatagramPacket</tt>.
   *
   * @param p the <tt>DatagramPacket</tt> to clone
   * @return a new <tt>DatagramPacket</tt> instance which is a clone of the specified
   *     <tt>DatagramPacket</tt>
   */
  public static DatagramPacket clone(DatagramPacket p) {
    synchronized (p) {
      byte[] pData = p.getData();
      byte[] cData = (pData == null) ? null : pData.clone();

      return new DatagramPacket(cData, p.getOffset(), p.getLength(), p.getAddress(), p.getPort());
    }
  }
 @Override
 protected int peek(InetAddress sender) throws IOException {
   // We don't actually want the data: we just want the DatagramPacket's filled-in address.
   DatagramPacket packet = new DatagramPacket(EmptyArray.BYTE, 0);
   int result = peekData(packet);
   // Note: evil side-effect on InetAddress! This method should have returned InetSocketAddress!
   sender.ipaddress = packet.getAddress().getAddress();
   return result;
 }
  private String lookupFarm() {
    if (Response != null) {

      if (Response.isStillValid()) {

        return Response.getFarmID();
      }

      Response = null;
    }

    try {
      InetAddress CDPServer;
      DatagramSocket Socket;
      CDPQuery Query;
      byte[] Buffer;
      DatagramPacket Packet;

      /* Get the IP address of the CDP servers. */
      CDPServer = InetAddress.getByName(CDPServerName);

      /* Create a UDP socket for the CDP query. */
      Socket = new DatagramSocket();
      Socket.setSoTimeout(CDPTimeout);

      /* Build the CDP query. */
      Query = new CDPQuery(Constants.AZUREUS_NAME + " " + Constants.AZUREUS_VERSION);
      Buffer = Query.getBytes();
      Packet = new DatagramPacket(Buffer, Buffer.length, CDPServer, CDPPort);

      /* Send the query to the CDP server. */
      Socket.send(Packet);

      /* Receive the CDP response. */
      Buffer = new byte[CDPResponse.MaxSize];
      Packet.setData(Buffer);
      Socket.receive(Packet);
      if (Packet.getAddress() != CDPServer || Packet.getPort() != CDPPort)
        throw (new Exception("CDP server address mismatch on response"));

      /* Parse the CDP response. */
      Response = new CDPResponse(Packet.getData());

      /* Return the farmID from the CDP response. */
      return Response.getFarmID();
    } catch (Throwable Excpt) {

      if (Excpt instanceof UnknownHostException) {

      } else {

        Excpt.printStackTrace();
      }

      return "default";
    }
  }
Beispiel #22
0
 public static DatagramPacket makePacket(char c1[], InetAddress inetAddress) {
   // byte[] sendMsg=(c1).toString().getBytes();
   String s1 = new String(c1);
   System.out.println(c1);
   byte[] sendMsg = s1.getBytes();
   DatagramPacket packet =
       new DatagramPacket(sendMsg, sendMsg.length, inetAddress, client.PORT_NUMBER_CLIENT);
   System.out.println(new String(packet.getData()));
   return packet;
 }
  protected void sendGuardSignal() throws IOException {
    final DatagramSocket guard;
    final DatagramPacket guardPacket;

    guard = new DatagramSocket();
    guardPacket = new DatagramPacket(new byte[0], 0);
    guardPacket.setSocketAddress(getLocalAddress());
    guard.send(guardPacket);
    guard.close();
  }
  public void respond(DatagramPacket packet) {

    byte[] data = new byte[packet.getLength()];
    System.arraycopy(packet.getData(), 0, data, 0, packet.getLength());
    try {
      String s = new String(data, "8859_1");
      System.out.println(packet.getAddress() + " at port " + packet.getPort() + " says " + s);
    } catch (java.io.UnsupportedEncodingException ex) {
      // This shouldn't happen
    }
  }
Beispiel #25
0
  public static void main(String args[]) throws Exception {
    DatagramSocket ds = new DatagramSocket(3000);
    byte[] buf = new byte[1024];

    DatagramPacket dp = new DatagramPacket(buf, 1024);
    ds.receive(dp);

    String str = new String(dp.getData(), 0, dp.getLength());
    System.out.println(str);
    ds.close();
  }
    SNMP_Parser(DatagramPacket dp) {
      data = new byte[dp.getLength()];

      int i;

      for (i = 0; i < dp.getLength(); i++) {
        data[i] = dp.getData()[i];
      }

      pointer = 0;
      data_remaining = data.length;
    }
 public static void main(String[] args) throws Exception {
   InetAddress addr = InetAddress.getByName("230.0.0.1");
   MulticastSocket soc = new MulticastSocket(2056);
   soc.joinGroup(addr);
   DatagramPacket dp = new DatagramPacket(new byte[80], 80);
   for (int i = 0; i < 5; i++) {
     soc.receive(dp);
     String msg = new String(dp.getData(), 0, dp.getLength());
     System.out.println(msg);
   }
   soc.leaveGroup(addr);
   soc.close();
 }
Beispiel #28
0
 public static void main(String[] args) {
   try (DatagramSocket socket = new DatagramSocket(0)) {
     socket.setSoTimeout(10000);
     InetAddress host = InetAddress.getByName(HOSTNAME);
     DatagramPacket request = new DatagramPacket(new byte[1], 1, host, PORT);
     DatagramPacket response = new DatagramPacket(new byte[1024], 1024);
     socket.send(request);
     socket.receive(response);
     String result = new String(response.getData(), 0, response.getLength(), "US-ASCII");
     System.out.println(result);
   } catch (IOException ex) {
     ex.printStackTrace();
   }
 }
 private void doRecv(DatagramPacket pack, int flags) throws IOException {
   IoBridge.recvfrom(
       false,
       fd,
       pack.getData(),
       pack.getOffset(),
       pack.getLength(),
       flags,
       pack,
       isNativeConnected);
   if (isNativeConnected) {
     updatePacketRecvAddress(pack);
   }
 }
  /**
   * Reads and returns a {@link DatagramPacket} from the underlying channel.
   *
   * @return the datagram packet read having the sender address.
   */
  @Override
  public DatagramPacket read(SelectionKey key) throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    SocketAddress sender = ((DatagramChannel) key.channel()).receive(buffer);

    /*
     * It is required to create a DatagramPacket because we need to preserve which socket address
     * acts as destination for sending reply packets.
     */
    buffer.flip();
    DatagramPacket packet = new DatagramPacket(buffer);
    packet.setSender(sender);

    return packet;
  }