Example #1
0
  // Check if DatagramChannel.send while connected can include
  // address without throwing
  private static void test1() 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);

    ByteBuffer bb = ByteBuffer.allocate(256);
    bb.put("hello".getBytes());
    bb.flip();
    int sent = sndChannel.send(bb, receiver);
    bb.clear();
    rcvChannel.receive(bb);
    bb.flip();
    CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
    if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed");

    rcvChannel.close();
    sndChannel.close();
  }
Example #2
0
  // Test the connected case to see if PUE is thrown
  public static void test2() throws Exception {

    setup();
    server.configureBlocking(true);
    server.connect(isa);
    server.configureBlocking(false);
    outBuf.rewind();
    server.write(outBuf);
    server.receive(inBuf);

    client.close();
    Thread.sleep(2000);
    outBuf.rewind();

    try {
      server.write(outBuf);
      Thread.sleep(2000);
      inBuf.clear();
      server.read(inBuf);
      if (onSolarisOrLinux()) throw new Exception("Expected PUE not thrown");
    } catch (PortUnreachableException pue) {
      System.err.println("received PUE");
    }
    server.close();
  }
Example #3
0
  void isReadable(SelectionKey k) {
    EventableChannel ec = (EventableChannel) k.attachment();
    long b = ec.getBinding();

    if (ec.isWatchOnly()) {
      if (ec.isNotifyReadable()) eventCallback(b, EM_CONNECTION_NOTIFY_READABLE, null);
    } else {
      myReadBuffer.clear();

      try {
        ec.readInboundData(myReadBuffer);
        myReadBuffer.flip();
        if (myReadBuffer.limit() > 0) {
          if (ProxyConnections != null) {
            EventableChannel target = ProxyConnections.get(b);
            if (target != null) {
              ByteBuffer myWriteBuffer = ByteBuffer.allocate(myReadBuffer.limit());
              myWriteBuffer.put(myReadBuffer);
              myWriteBuffer.flip();
              target.scheduleOutboundData(myWriteBuffer);
            } else {
              eventCallback(b, EM_CONNECTION_READ, myReadBuffer);
            }
          } else {
            eventCallback(b, EM_CONNECTION_READ, myReadBuffer);
          }
        }
      } catch (IOException e) {
        UnboundConnections.add(b);
      }
    }
  }
  public static void main(String[] args) throws Exception {
    DatagramChannel dc = DatagramChannel.open();
    DatagramSocket socket = dc.socket();
    socket.bind(new InetSocketAddress(22500));
    ByteBuffer byteBuf = ByteBuffer.allocate(8);
    //        byteBuf.order(ByteOrder.LITTLE_ENDIAN);
    LongBuffer longBuf = byteBuf.asLongBuffer();

    while (true) {
      dc.receive(byteBuf);
      System.out.println(longBuf.get(0));
      byteBuf.clear();
    }
  }
Example #5
0
  void isReadable(SelectionKey k) {
    EventableChannel ec = (EventableChannel) k.attachment();
    long b = ec.getBinding();

    if (ec.isWatchOnly()) {
      if (ec.isNotifyReadable()) eventCallback(b, EM_CONNECTION_NOTIFY_READABLE, null);
    } else {
      myReadBuffer.clear();

      try {
        ec.readInboundData(myReadBuffer);
        myReadBuffer.flip();
        if (myReadBuffer.limit() > 0) eventCallback(b, EM_CONNECTION_READ, myReadBuffer);
      } catch (IOException e) {
        UnboundConnections.add(b);
      }
    }
  }
 protected synchronized Message receiveMessage() throws IOException {
   if (messageBuffer.size() > 0) {
     Message m = (Message) messageBuffer.get(0);
     messageBuffer.remove(0);
     return m;
   }
   try {
     InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer);
     if (remoteAddress != null) {
       int len = receiveBuffer.position();
       receiveBuffer.rewind();
       receiveBuffer.get(buf, 0, len);
       try {
         IP address = IP.fromInetAddress(remoteAddress.getAddress());
         int port = remoteAddress.getPort();
         extractor.appendData(buf, 0, len, new SocketDescriptor(address, port));
         receiveBuffer.clear();
         extractor.updateAvailableMessages();
         return extractor.nextMessage();
       } catch (EOFException exc) {
         exc.printStackTrace();
         System.err.println(buf.length + ", " + len);
       } catch (InvocationTargetException exc) {
         exc.printStackTrace();
       } catch (IllegalAccessException exc) {
         exc.printStackTrace();
       } catch (InstantiationException exc) {
         exc.printStackTrace();
       } catch (IllegalArgumentException e) {
         e.printStackTrace();
       } catch (InvalidCompressionMethodException e) {
         e.printStackTrace();
       }
     }
   } catch (ClosedChannelException exc) {
     if (isKeepAlive()) {
       throw exc;
     }
   }
   return null;
 }
  public void resendMessage(Message message, IP remoteAddress, int remotePort) throws IOException {
    if (remoteAddress == null) remoteAddress = IP.getLocalHost();

    message.setSentStamp(getConvertedTime(remoteAddress, remotePort));
    message.setMessageServer(this);
    try {
      sendBuffer.clear();
      sendBuffer.put(extractor.convertMessage(message));
      sendBuffer.flip();
      channel.send(sendBuffer, new InetSocketAddress(remoteAddress.toString(), remotePort));
      message.setRemoteAddress(remoteAddress);
      message.setRemotePort(remotePort);
      messageSent(message);
    } catch (IllegalAccessException exc) {
      throw new RuntimeException(exc);
    } catch (IllegalArgumentException exc) {
      throw new RuntimeException(exc);
    } catch (InvocationTargetException exc) {
      throw new RuntimeException(exc);
    }
  }
  private void go() throws IOException {
    // Create a new selector
    Selector selector = Selector.open();

    // Open a listener on each port, and register each one
    // with the selector
    for (int i = 0; i < ports.length; ++i) {
      ServerSocketChannel ssc = ServerSocketChannel.open();
      ssc.configureBlocking(false);
      ServerSocket ss = ssc.socket();
      InetSocketAddress address = new InetSocketAddress(ports[i]);
      ss.bind(address);

      SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT);

      System.out.println("Going to listen on " + ports[i]);
    }

    while (true) {
      int num = selector.select();

      Set selectedKeys = selector.selectedKeys();
      Iterator it = selectedKeys.iterator();

      while (it.hasNext()) {
        SelectionKey key = (SelectionKey) it.next();

        if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
          // Accept the new connection
          ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
          SocketChannel sc = ssc.accept();
          sc.configureBlocking(false);

          // Add the new connection to the selector
          SelectionKey newKey = sc.register(selector, SelectionKey.OP_READ);
          it.remove();

          System.out.println("Got connection from " + sc);
        } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
          // Read the data
          SocketChannel sc = (SocketChannel) key.channel();

          // Echo data
          int bytesEchoed = 0;
          while (true) {
            echoBuffer.clear();

            int r = sc.read(echoBuffer);

            if (r <= 0) {
              break;
            }

            echoBuffer.flip();

            sc.write(echoBuffer);
            bytesEchoed += r;
          }

          System.out.println("Echoed " + bytesEchoed + " from " + sc);

          it.remove();
        }
      }

      // System.out.println( "going to clear" );
      //      selectedKeys.clear();
      // System.out.println( "cleared" );
    }
  }
Example #9
0
  public static void main(String[] args) {
    try {
      System.out.println("CliTest.java");
      // create TCP socket channel
      SocketChannel channel = SocketChannel.open();
      System.out.println("CliTest.java: channel created");
      channel.connect(new InetSocketAddress("localhost", PORT));
      System.out.println("CliTest.java: channel socket connected");
      System.out.println();

      // create  & send a login message
      byte[] bytes = LoginMessage.getLoginMessage("user1", "password1");
      System.out.println("CliTest.java: login message created");
      System.out.println(LoginMessage.getMessageString(bytes));
      System.out.printf("CliTest.java: login message length in bytes: %d\n", bytes.length);
      ByteBuffer buf = ByteBuffer.allocate(4096);
      buf.put(bytes);
      buf.flip();
      // System.out.printf("CliTest.java: buf.remaining before channel.write(): %d\n",
      // buf.remaining());
      int numwritten = channel.write(buf);
      System.out.printf(
          "CliTest.java: login mesage written: number of bytes written: %d\n", numwritten);

      // read reply message
      buf.clear();
      int numread = channel.read(buf);
      bytes = new byte[numread];
      buf.flip();
      buf.get(bytes);
      if (LoginMessage.isLoginSuccessMessage(bytes)) {
        System.out.printf(
            "CliTest.java: first message read: Success Message: number of bytes read: %d\n",
            numread);
        // get remote port number from success message
        int port = LoginMessage.getPort(bytes);
        System.out.printf("Port Number: %d\n", port);
        byte playerid = LoginMessage.getPlayerId(bytes);
        System.out.printf("Player id: %d\n", playerid);
        String mcastString = LoginMessage.getMulticastAddress(bytes);
        System.out.printf("Multicast Address: %s\n", mcastString);
        // create datagram channel & connect to rem port
        DatagramChannel dchannel = DatagramChannel.open();
        dchannel.socket().bind(new InetSocketAddress(0));
        dchannel.socket().connect(new InetSocketAddress(channel.socket().getInetAddress(), port));
        // get localport of datagram socket
        int localport = dchannel.socket().getLocalPort();
        System.out.printf("UDP local port: %d\n", localport);
        // send success message to send port number to server
        bytes = LoginMessage.getLoginSuccessMessage(playerid, null, localport);
        buf.clear();
        buf.put(bytes);
        buf.flip();
        channel.write(buf);

        DeathMessage dm = new DeathMessage((byte) 1, (byte) 1);
        bytes = dm.getByteMessage();
        buf.clear();
        buf.put(bytes);
        buf.flip();
        channel.write(buf);
      } else {
        System.out.printf(
            "CliTest.java: first message read: NOT Success Message: number of bytes read: %d\n",
            numread);
      }
      channel.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }