Ejemplo n.º 1
0
  /**
   * Opens a server TCP connection to clients. Creates, binds, and listens
   *
   * @param port local TCP port to listen on
   * @param backlog listen backlog.
   * @return a native handle to the network connection.
   * @throws IOException
   */
  public int openServer(int port, int backlog) throws IOException {
    int fd = -1;

    fd = sockets.socket(Socket.AF_INET, Socket.SOCK_STREAM, 0);
    if (DEBUG) {
      System.err.println("Socket.socket() = " + fd);
    }
    if (fd < 0) {
      throw newError(fd, "socket create");
    }

    set_blocking_flags(fd, /*is_blocking*/ false);

    setSockOpt(fd, Socket.SO_REUSEADDR, 1);

    setSockOpt(fd, Socket.IPPROTO_TCP, Socket.TCP_NODELAY, 1);

    Socket.sockaddr_in local_sin = new Socket.sockaddr_in();
    local_sin.sin_family = Socket.AF_INET;
    local_sin.sin_port = Inet.htons((short) port);
    local_sin.sin_addr = Socket.INADDR_ANY;
    if (DEBUG) {
      System.err.println("Socket.bind(" + fd + ", " + local_sin + ")");
    }

    if (sockets.bind(fd, local_sin, local_sin.size()) < 0) {
      throw newError(fd, "bind");
    }

    if (sockets.listen(fd, backlog) < 0) {
      throw newError(fd, "listen");
    }

    return fd;
  }
Ejemplo n.º 2
0
 /**
  * Initializes {@link Socket} instances for each namespaces.
  *
  * @param nsp namespace.
  * @return a socket instance for the namespace.
  */
 public Socket socket(String nsp) {
   Socket socket = this.nsps.get(nsp);
   if (socket == null) {
     socket = new Socket(this, nsp);
     Socket _socket = this.nsps.putIfAbsent(nsp, socket);
     if (_socket != null) {
       socket = _socket;
     } else {
       final Manager self = this;
       final Socket s = socket;
       socket.on(
           Socket.EVENT_CONNECTING,
           new Listener() {
             @Override
             public void call(Object... args) {
               self.connecting.add(s);
             }
           });
       socket.on(
           Socket.EVENT_CONNECT,
           new Listener() {
             @Override
             public void call(Object... objects) {
               s.id = self.engine.id();
             }
           });
     }
   }
   return socket;
 }
  @Test(timeout = TIMEOUT)
  public void notSendPacketsIfSocketCloses() throws InterruptedException {
    final BlockingQueue<Object> values = new LinkedBlockingQueue<Object>();

    socket = new Socket(createOptions());
    socket.on(
        Socket.EVENT_OPEN,
        new Emitter.Listener() {
          @Override
          public void call(Object... args) {
            final boolean[] noPacket = new boolean[] {true};
            socket.on(
                Socket.EVENT_PACKET_CREATE,
                new Emitter.Listener() {
                  @Override
                  public void call(Object... args) {
                    noPacket[0] = false;
                  }
                });
            socket.close();
            Timer timer = new Timer();
            timer.schedule(
                new TimerTask() {
                  @Override
                  public void run() {
                    values.offer(noPacket[0]);
                  }
                },
                1200);
          }
        });
    socket.open();
    assertThat((Boolean) values.take(), is(true));
  }
  @Test(timeout = TIMEOUT)
  public void connectToLocalhost() throws InterruptedException {
    final BlockingQueue<Object> values = new LinkedBlockingQueue<Object>();

    socket = new Socket(createOptions());
    socket.on(
        Socket.EVENT_OPEN,
        new Emitter.Listener() {
          @Override
          public void call(Object... args) {
            socket.on(
                Socket.EVENT_MESSAGE,
                new Emitter.Listener() {
                  @Override
                  public void call(Object... args) {
                    values.offer(args[0]);
                    socket.close();
                  }
                });
          }
        });
    socket.open();

    assertThat((String) values.take(), is("hi"));
  }
  @Test(timeout = TIMEOUT)
  public void receiveMultibyteUTF8StringsWithPolling() throws InterruptedException {
    final BlockingQueue<Object> values = new LinkedBlockingQueue<Object>();

    socket = new Socket(createOptions());
    socket.on(
        Socket.EVENT_OPEN,
        new Emitter.Listener() {
          @Override
          public void call(Object... args) {
            socket.send("cash money €€€");
            socket.on(
                Socket.EVENT_MESSAGE,
                new Emitter.Listener() {
                  @Override
                  public void call(Object... args) {
                    if ("hi".equals(args[0])) return;
                    values.offer(args[0]);
                    socket.close();
                  }
                });
          }
        });
    socket.open();

    assertThat((String) values.take(), is("cash money €€€"));
  }
  @Test(timeout = TIMEOUT)
  public void receiveEmoji() throws InterruptedException {
    final BlockingQueue<Object> values = new LinkedBlockingQueue<Object>();

    socket = new Socket(createOptions());
    socket.on(
        Socket.EVENT_OPEN,
        new Emitter.Listener() {
          @Override
          public void call(Object... args) {
            socket.send("\uD800-\uDB7F\uDB80-\uDBFF\uDC00-\uDFFF\uE000-\uF8FF");
            socket.on(
                Socket.EVENT_MESSAGE,
                new Emitter.Listener() {
                  @Override
                  public void call(Object... args) {
                    if ("hi".equals(args[0])) return;
                    values.offer(args[0]);
                    socket.close();
                  }
                });
          }
        });
    socket.open();

    assertThat((String) values.take(), is("\uD800-\uDB7F\uDB80-\uDBFF\uDC00-\uDFFF\uE000-\uF8FF"));
  }
Ejemplo n.º 7
0
  /**
   * Opens a server TCP connection to clients. Creates, binds, and listens
   *
   * @param port local TCP port to listen on
   * @param backlog listen backlog.
   * @return a native handle to the network connection.
   * @throws IOException
   */
  public int openServer(int port, int backlog) throws IOException {
    int fd = -1;

    fd = Socket.INSTANCE.socket(Socket.AF_INET, Socket.SOCK_STREAM, 0);
    if (fd < 0) {
      throw newError(fd, "socket create");
    }

    set_blocking_flags(fd, /*is_blocking*/ false);

    IntByReference option_val = new IntByReference(1);
    if (sockets.setsockopt(fd, Socket.SOL_SOCKET, Socket.SO_REUSEADDR, option_val, 4) < 0) {
      throw newError(fd, "setSockOpt");
    }
    option_val.free();

    Socket.sockaddr_in local_sin = new Socket.sockaddr_in();
    local_sin.sin_family = Socket.AF_INET;
    local_sin.sin_port = Inet.htons((short) port);
    local_sin.sin_addr = Socket.INADDR_ANY;
    if (sockets.bind(fd, local_sin) < 0) {
      throw newError(fd, "bind");
    }

    if (sockets.listen(fd, backlog) < 0) {
      throw newError(fd, "listen");
    }

    return fd;
  }
Ejemplo n.º 8
0
 public static void send(Socket socket, Message msg) throws IOException {
   int bufferSize = socket.getMaxMessageBufferSize();
   byte[] bytes = encode(msg);
   boolean last;
   for (int offset = 0; offset < bytes.length; offset += bufferSize) {
     last = bytes.length <= offset + bufferSize;
     int length = last ? bytes.length - offset : bufferSize;
     socket.sendPartialBytes(ByteBuffer.wrap(bytes, offset, length), last);
   }
 }
Ejemplo n.º 9
0
 /**
  * Wrapper for send method of socket
  *
  * @param data Data array
  * @param dest Destination address
  */
 public void send(byte[] data, InetAddress dest) {
   try {
     socket.send(data, dest);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 10
0
 /**
  * Wrapper for broadcast method of socket
  *
  * @param data Data array
  */
 public void broadcast(byte[] data) {
   try {
     socket.broadcast(data);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 11
0
  /**
   * set a socket option
   *
   * @param socket socket descriptor
   * @param level Socket.SOL_SOCKET, etc.
   * @param option_name
   * @param option_value new value
   * @throws IOException on error
   */
  public void setSockOpt(int socket, int level, int option_name, int option_value)
      throws IOException {
    IntByReference value = new IntByReference(option_value);
    if (false) Assert.that(option_value == value.getValue());
    if (DEBUG) {
      System.out.println(
          "setSockOpt(" + socket + ", " + level + ", " + option_name + ", " + option_value + ")");
    }
    int err = sockets.setsockopt(socket, level, option_name, value, 4);

    if (false) Assert.that(option_value == value.getValue());
    value.free();
    LibCUtil.errCheckNeg(err);

    if (DEBUG) {
      int newValue = getSockOpt(socket, level, option_name);
      if (option_value != newValue) {
        System.out.println(
            "FAILED: setSockOpt("
                + socket
                + ", "
                + level
                + ", "
                + option_name
                + ", "
                + option_value
                + ")");
        System.err.println("   Ended with: " + newValue);
      }
    }
  }
Ejemplo n.º 12
0
 /**
  * Takes an IPv4 Internet address and returns string representing the address in `.' notation
  *
  * @param in the opaque bytes of an IPv4 "struct in_addr"
  * @return String
  */
 public String inet_ntop(int in) {
   Pointer charBuf = new Pointer(Socket.INET_ADDRSTRLEN);
   IntByReference addrBuf = new IntByReference(in); // the addr is passed by value (to handle IPv6)
   String result = sockets.inet_ntop(Socket.AF_INET, addrBuf, charBuf, Socket.INET_ADDRSTRLEN);
   addrBuf.free();
   charBuf.free();
   return result;
 }
Ejemplo n.º 13
0
 /** @inheritDoc */
 public void close(int fd) throws IOException {
   // NOTE: this would block the VM. A real implementation should
   // make this a async native method.
   sockets.shutdown(fd, 2);
   libc.close(fd);
   if (DEBUG) {
     System.out.println("close(" + fd + ")");
   }
 }
Ejemplo n.º 14
0
 /**
  * Constructor of NetworkHandler
  *
  * @param port
  */
 public NetworkHandler(int port, ApplicationState state) {
   this.state = state;
   try {
     this.socket = new SocketImpl(port);
     socket.connect();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 15
0
  /** @inheritDoc */
  public int open(String hostname, int port, int mode) throws IOException {
    // init_sockets(); win32 only
    int fd = -1;

    fd = sockets.socket(Socket.AF_INET, Socket.SOCK_STREAM, 0);
    if (DEBUG) {
      System.err.println("Socket.socket() = " + fd);
    }
    if (fd < 0) {
      throw newError(fd, "socket create");
    }

    set_blocking_flags(fd, /*is_blocking*/ false);

    NetDB.hostent phostent;
    // hostname is always NUL terminated. See socket/Protocol.java for detail.
    phostent = NetDB.INSTANCE.gethostbyname(hostname);
    if (phostent == null) {
      throw newError(fd, "gethostbyname (herrono = " + NetDB.INSTANCE.h_errno() + ")");
    }

    Socket.sockaddr_in destination_sin = new Socket.sockaddr_in();
    destination_sin.sin_family = Socket.AF_INET;
    destination_sin.sin_port = Inet.htons((short) port);
    destination_sin.sin_addr = phostent.h_addr_list[0];

    if (DEBUG) {
      System.err.println("Socket.sockaddr_in: " + destination_sin);
      System.err.println("connect: hostname: " + hostname + " port: " + port + " mode: " + mode);
    }
    if (sockets.connect(fd, destination_sin, destination_sin.size()) < 0) {
      int err_code = LibCUtil.errno();
      if (err_code == LibC.EINPROGRESS || err_code == LibC.EWOULDBLOCK) {
        // When the socket is ready for connect, it becomes *writable*
        // (according to BSD socket spec of select())
        VMThread.getSystemEvents().waitForWriteEvent(fd);
      } else {
        throw newError(fd, "connect");
      }
    }

    return fd;
  }
Ejemplo n.º 16
0
 private Connection() {
   socket =
       new Socket(port) {
         public void onMessage(WebSocket conn, String message) {
           Log.d("MOCKERLOG", message);
           setChanged();
           notifyObservers(message);
         }
       };
   socket.start();
 }
Ejemplo n.º 17
0
  /**
   * Accept client connections on server socket fd. Blocks until a client connects.
   *
   * @param fd open server socket. See {@link #openServer}.
   * @return a native handle to the network connection.
   * @throws IOException
   */
  public int accept(int fd) throws IOException {
    Socket.sockaddr_in remote_sin = new Socket.sockaddr_in();
    IntByReference address_len = new IntByReference(4);
    int newSocket;

    try {
      if (DEBUG) {
        System.err.println("Socket.accept(" + fd + ", " + remote_sin + ")...");
      }

      newSocket = sockets.accept(fd, remote_sin, address_len);

      if (newSocket < 0) {
        if (DEBUG) {
          System.err.println("Need to block for accept...");
        }

        int err_code = LibCUtil.errno();
        if (err_code == LibC.EAGAIN || err_code == LibC.EWOULDBLOCK) {
          VMThread.getSystemEvents().waitForReadEvent(fd);
          newSocket = sockets.accept(fd, remote_sin, address_len);
          if (newSocket < 0) {
            throw newError(fd, "accept");
          }
        } else {
          // BUG!
          throw newError(fd, "accept");
        }
      }
    } finally {
      address_len.free();
    }

    set_blocking_flags(newSocket, /*is_blocking*/ false);
    // we could read info about client from remote_sin, but don't need to.

    if (DEBUG) {
      System.err.println("    Socket.accept(...) = " + newSocket);
    }
    return newSocket;
  }
  @Test(timeout = TIMEOUT)
  public void receiveBinaryDataAndMultibyteUTF8String() throws InterruptedException {
    final BlockingQueue<Object> values = new LinkedBlockingQueue<Object>();

    final byte[] binaryData = new byte[5];
    for (int i = 0; i < binaryData.length; i++) {
      binaryData[i] = (byte) i;
    }

    final int[] msg = new int[] {0};
    Socket.Options opts = new Socket.Options();
    opts.port = PORT;
    opts.transports = new String[] {Polling.NAME};
    socket = new Socket(opts);
    socket.on(
        Socket.EVENT_OPEN,
        new Emitter.Listener() {
          @Override
          public void call(Object... args) {
            socket.send(binaryData);
            socket.send("cash money €€€");
            socket.on(
                Socket.EVENT_MESSAGE,
                new Emitter.Listener() {
                  @Override
                  public void call(Object... args) {
                    if ("hi".equals(args[0])) return;

                    values.offer(args[0]);
                    msg[0]++;
                  }
                });
          }
        });
    socket.open();

    assertThat((byte[]) values.take(), is(binaryData));
    assertThat((String) values.take(), is("cash money €€€"));
    socket.close();
  }
Ejemplo n.º 19
0
 /** Read errno, try to clean up fd, and create exception. */
 private IOException newError(int fd, String msg) {
   if (DEBUG) {
     VM.print(msg);
     VM.print(": errno: ");
   }
   int err_code = LibCUtil.errno();
   if (DEBUG) {
     VM.print(err_code);
     VM.println();
   }
   sockets.shutdown(fd, 2);
   libc.close(fd);
   return new IOException(" errno: " + err_code + " on fd: " + fd + " during " + msg);
 }
Ejemplo n.º 20
0
  /**
   * get a socket option
   *
   * @param socket socket descriptor
   * @param option_name
   * @throws IOException on error
   */
  public int getSockOpt(int socket, int option_name) throws IOException {
    IntByReference value = new IntByReference(0);
    IntByReference opt_len = new IntByReference(4);
    if (DEBUG) {
      System.out.println("getsockopt(" + socket + ", " + option_name + ")");
    }

    int err = sockets.getsockopt(socket, Socket.SOL_SOCKET, option_name, value, opt_len);
    int result = value.getValue();
    value.free();
    if (false) Assert.that(opt_len.getValue() == 4);
    opt_len.free();
    LibCUtil.errCheckNeg(err);
    return result;
  }
Ejemplo n.º 21
0
  /**
   * Accept client connections on server socket fd. Blocks until a client connects.
   *
   * @param fd open server socket. See {@link #openServer}.
   * @return a native handle to the network connection.
   * @throws IOException
   */
  public int accept(int fd) throws IOException {
    VMThread.getSystemEvents().waitForReadEvent(fd);

    Socket.sockaddr_in remote_sin = new Socket.sockaddr_in();
    IntByReference address_len = new IntByReference(4);
    int newSocket = sockets.accept(fd, remote_sin, address_len);
    if (newSocket < 0) {
      throw newError(fd, "accept");
    }
    address_len.free();
    set_blocking_flags(newSocket, /*is_blocking*/ false);
    // we could read info about client from remote_sin, but don't need to.

    return newSocket;
  }
Ejemplo n.º 22
0
  @Override
  public void run() {
    while (listening) {
      Packet packet = null;
      try {
        packet = socket.receive();
      } catch (InterruptedException e) {
        e.printStackTrace();
        continue;
      }

      Message message = new Gson().fromJson(new String(packet.getData()), Message.class);

      String packetData = new String(packet.getData());
      switch (message.getType()) {
        case NickChangeMessage.TYPE:
          NickChangeMessage nickChangeMessage =
              new Gson().fromJson(packetData, NickChangeMessage.class);
          state.addUser(nickChangeMessage, packet.getSourceAddress());
          break;
        case TextMessage.TYPE:
          TextMessage textMessage = new Gson().fromJson(packetData, TextMessage.class);
          state.receiveMessage(textMessage, packet.getSourceAddress());
          break;
        case LeaveMessage.TYPE:
          LeaveMessage leaveMessage = new Gson().fromJson(packetData, LeaveMessage.class);
          state.userLeft(leaveMessage);
          break;
        case InviteMessage.TYPE:
          InviteMessage inviteMessage = new Gson().fromJson(packetData, InviteMessage.class);
          state.invite(inviteMessage);
          break;
        case RequestNickMessage.TYPE:
          RequestNickMessage requestNickMessage =
              new Gson().fromJson(packetData, RequestNickMessage.class);
          state.requestNick(requestNickMessage, packet.getSourceAddress());
          break;
        case LeaveConversationMessage.TYPE:
          LeaveConversationMessage leaveConversationMessage =
              new Gson().fromJson(packetData, LeaveConversationMessage.class);
          state.leaveConversation(leaveConversationMessage);
          break;
      }
    }
  }
Ejemplo n.º 23
0
 /**
  * set a socket option
  *
  * @param socket socket descriptor
  * @param option_name
  * @param option_value new value
  * @throws IOException on error
  */
 public void setSockOpt(int socket, int option_name, int option_value) throws IOException {
   IntByReference value = new IntByReference(option_value);
   int err = sockets.setsockopt(socket, Socket.SOL_SOCKET, option_name, value, 4);
   value.free();
   LibCUtil.errCheckNeg(err);
 }
Ejemplo n.º 24
0
  @Override
  public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
    Socket socket = (Socket) component;
    String channel = socket.getChannel();
    String channelUrl = Constants.PUSH_PATH + channel;
    String url = getResourceURL(context, channelUrl);
    String pushServer =
        RequestContext.getCurrentInstance().getApplicationContext().getConfig().getPushServerURL();
    String clientId = socket.getClientId(context);

    if (pushServer != null) {
      url = pushServer + url;
    }

    WidgetBuilder wb = getWidgetBuilder(context);
    wb.initWithDomReady("Socket", socket.resolveWidgetVar(), clientId);

    wb.attr("url", url)
        .attr("autoConnect", socket.isAutoConnect())
        .attr("transport", socket.getTransport())
        .attr("fallbackTransport", socket.getFallbackTransport())
        .callback("onMessage", socket.getOnMessage())
        .callback("onError", "function(response)", socket.getOnError())
        .callback("onClose", "function(response)", socket.getOnClose())
        .callback("onOpen", "function(response)", socket.getOnOpen())
        .callback("onReconnect", "function(response)", socket.getOnReconnect())
        .callback("onMessagePublished", "function(response)", socket.getOnMessagePublished())
        .callback(
            "onTransportFailure", "function(response, request)", socket.getOnTransportFailure())
        .callback("onLocalMessage", "function(response)", socket.getOnLocalMessage());

    encodeClientBehaviors(context, socket);

    wb.finish();
  }
Ejemplo n.º 25
0
 public TCP(String host, int port) {
   jsObj = Socket.get().createTCP(host, port).getJsObj();
 }
Ejemplo n.º 26
0
 private void emitAll(String event, Object... args) {
   this.emit(event, args);
   for (Socket socket : this.nsps.values()) {
     socket.emit(event, args);
   }
 }
Ejemplo n.º 27
0
 /** Update `socket.id` of all sockets */
 private void updateSocketIds() {
   for (Socket socket : this.nsps.values()) {
     socket.id = this.engine.id();
   }
 }