Esempio n. 1
0
 @Override
 public void run() {
   try {
     start_server();
   } catch (IOException e) {
     Main.log("SNServer> IOException: " + e);
     // TODO handle exception
   }
 }
Esempio n. 2
0
  /**
   * Procedure OP_ACCEPT of selector
   *
   * @param key Key of this server
   * @throws IOException
   */
  private void accept(SelectionKey key) throws IOException {
    ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
    SocketChannel channel = serverChannel.accept();
    channel.configureBlocking(false);

    // send_message(key, "Welcome."); //DEBUG
    Socket socket = channel.socket();
    SocketAddress remoteAddr = socket.getRemoteSocketAddress();
    Main.log("Connected to: " + remoteAddr); // DEBUG

    register_connection(channel);
  }
Esempio n. 3
0
  private void start_server() throws IOException {
    // create selector and channel
    selector = Selector.open();
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);

    // bind to port
    InetSocketAddress listenAddr = new InetSocketAddress((InetAddress) null, port);
    serverChannel.socket().bind(listenAddr);
    serverChannel.register(selector, SelectionKey.OP_ACCEPT);

    Main.log("Echo server ready. Ctrl-C to stop.");
    main();
  }
Esempio n. 4
0
  private void read(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel) key.channel();

    // repeatedly read from channel until no more data is available
    while (true) {
      ByteBuffer buffer = ByteBuffer.allocate(8192);
      int numRead = -1;
      try {
        numRead = channel.read(buffer);
      } catch (IOException e) {
        e.printStackTrace();
      }
      // nothing to read
      if (numRead == 0) break;
      // connection closed
      if (numRead == -1) {
        to_send.remove(channel);
        Socket socket = channel.socket();
        SocketAddress remoteAddr = socket.getRemoteSocketAddress();
        Main.log("Connection closed by client: " + remoteAddr); // TODO handle
        channel.close();
        return;
      }
      // add new data to 'in_buffer'
      byte[] data = new byte[numRead];
      System.arraycopy(buffer.array(), 0, data, 0, numRead);
      in_buffer.append(new String(data, "utf-8"));
    }

    // check if there are complete messages in 'in_buffer'
    while (true) {
      int pos = in_buffer.indexOf("\n");
      if (pos == -1) break;
      in_msg.add(new RawMessage(RawMessage.Type.CLIENT_MSG, in_buffer.substring(0, pos)));
      in_buffer.delete(0, pos + 1);
    }
  }