Java Code Examples for java.nio.channels.ServerSocketChannel#bind()

The following examples show how to use java.nio.channels.ServerSocketChannel#bind() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SingleSocketTcpWriterTest.java    From kieker with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConnectWithDefault() throws Exception {
	final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
	try {
		serverSocketChannel.bind(new InetSocketAddress(HOSTNAME, PORT));
		serverSocketChannel.configureBlocking(false);
		serverSocketChannel.accept(); // non-blocking accept

		final SingleSocketTcpWriter writer = new SingleSocketTcpWriter(this.configuration);
		try {
			writer.onStarting();
		} finally {
			writer.onTerminating();
		}
	} finally {
		serverSocketChannel.close();
	}

	Assert.assertTrue(true); // NOPMD (this test should not throw any exception)
}
 
Example 2
Source File: AsynchronousEcho.java    From vertx-in-action with MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException {
  Selector selector = Selector.open();

  ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
  serverSocketChannel.bind(new InetSocketAddress(3000));
  serverSocketChannel.configureBlocking(false);
  serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

  while (true) {
    selector.select();
    Iterator<SelectionKey> it = selector.selectedKeys().iterator();
    while (it.hasNext()) {
      SelectionKey key = it.next();
      if (key.isAcceptable()) {
        newConnection(selector, key);
      } else if (key.isReadable()) {
        echo(key);
      } else if (key.isWritable()) {
        continueEcho(selector, key);
      }
      it.remove();
    }
  }
}
 
Example 3
Source File: ChannelListener.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a server socket channel for listening to connections.
 *
 * @param nicIPAddress - if null binds to wildcard address
 * @param port - port to bind to
 * @param receiveBufferSize - size of OS receive buffer to request. If less
 * than 0 then will not be set and OS default will win.
 * @throws IOException if unable to add socket
 */
public void addServerSocket(final InetAddress nicIPAddress, final int port, final int receiveBufferSize)
        throws IOException {
    final ServerSocketChannel ssChannel = ServerSocketChannel.open();
    ssChannel.configureBlocking(false);
    if (receiveBufferSize > 0) {
        ssChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
        final int actualReceiveBufSize = ssChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < receiveBufferSize) {
            LOGGER.warn(this + " attempted to set TCP Receive Buffer Size to "
                    + receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }
    ssChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    ssChannel.bind(new InetSocketAddress(nicIPAddress, port));
    ssChannel.register(serverSocketSelector, SelectionKey.OP_ACCEPT);
}
 
Example 4
Source File: ReactorEchoServerV2.java    From new-bull with MIT License 6 votes vote down vote up
@Override
public void start(int port) throws IOException {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.bind(new InetSocketAddress("0.0.0.0", port));
    serverSocketChannel.configureBlocking(false);

    acceptReactor = new Reactor();
    acceptReactor.start();

    subReactors = new Reactor[5];
    for (int i = 0; i < subReactors.length; i++) {
        subReactors[i] = new Reactor();
        subReactors[i].start();
    }

    Acceptor acceptor = new Acceptor(subReactors);
    acceptReactor.register(serverSocketChannel, SelectionKey.OP_ACCEPT, acceptor);

}
 
Example 5
Source File: EchoMultiServerMain.java    From Chronicle-Network with Apache License 2.0 6 votes vote down vote up
public static void main(@NotNull String... args) throws IOException {
    int port = args.length < 1 ? EchoClientMain.PORT : Integer.parseInt(args[0]);
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.bind(new InetSocketAddress(port));
    System.out.println("listening on " + ssc);
    ExecutorService service = new ThreadPoolExecutor(0, 1000,
            60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(),
            new NamedThreadFactory("connections", true));
    ((ThreadPoolExecutor) service).setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

    while (true) {
        final SocketChannel socket = ssc.accept();
        socket.socket().setTcpNoDelay(true);
        socket.configureBlocking(true);
        service.submit(() -> process(socket));
    }
}
 
Example 6
Source File: ChannelListener.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a server socket channel for listening to connections.
 *
 * @param nicIPAddress - if null binds to wildcard address
 * @param port - port to bind to
 * @param receiveBufferSize - size of OS receive buffer to request. If less
 * than 0 then will not be set and OS default will win.
 * @throws IOException if unable to add socket
 */
public void addServerSocket(final InetAddress nicIPAddress, final int port, final int receiveBufferSize)
        throws IOException {
    final ServerSocketChannel ssChannel = ServerSocketChannel.open();
    ssChannel.configureBlocking(false);
    if (receiveBufferSize > 0) {
        ssChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
        final int actualReceiveBufSize = ssChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < receiveBufferSize) {
            LOGGER.warn(this + " attempted to set TCP Receive Buffer Size to "
                    + receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }
    ssChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    ssChannel.bind(new InetSocketAddress(nicIPAddress, port));
    ssChannel.register(serverSocketSelector, SelectionKey.OP_ACCEPT);
}
 
Example 7
Source File: TestBlockingNIO.java    From code with Apache License 2.0 5 votes vote down vote up
@Test
public void server() throws IOException{
    //1. 获取通道
    ServerSocketChannel ssChannel = ServerSocketChannel.open();

    FileChannel outChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);

    //2. 绑定连接
    ssChannel.bind(new InetSocketAddress(9898));

    //3. 获取客户端连接的通道
    SocketChannel sChannel = ssChannel.accept();

    //4. 分配指定大小的缓冲区
    ByteBuffer buf = ByteBuffer.allocate(1024);

    //5. 接收客户端的数据,并保存到本地
    while(sChannel.read(buf) != -1){
        buf.flip();
        outChannel.write(buf);
        buf.clear();
    }

    //6. 关闭通道
    sChannel.close();
    outChannel.close();
    ssChannel.close();

}
 
Example 8
Source File: EchoServer.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    Selector selector = Selector.open();
    ServerSocketChannel serverSocket = ServerSocketChannel.open();
    serverSocket.bind(new InetSocketAddress("localhost", 5454));
    serverSocket.configureBlocking(false);
    serverSocket.register(selector, SelectionKey.OP_ACCEPT);
    ByteBuffer buffer = ByteBuffer.allocate(256);

    while (true) {
        selector.select();
        Set<SelectionKey> selectedKeys = selector.selectedKeys();
        Iterator<SelectionKey> iter = selectedKeys.iterator();
        while (iter.hasNext()) {

            SelectionKey key = iter.next();

            if (key.isAcceptable()) {
                register(selector, serverSocket);
            }

            if (key.isReadable()) {
                answerWithEcho(buffer, key);
            }
            iter.remove();
        }
    }
}
 
Example 9
Source File: AcceptorImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
protected AcceptorImpl(Reactor reactor, String host, int port, Handler handler) throws IOException {
    ServerSocketChannel ssc = ((ReactorImpl)reactor).getIO().serverSocketChannel();
    ssc.bind(new InetSocketAddress(host, port));
    sel = ((ReactorImpl)reactor).selectable(this);
    sel.setChannel(ssc);
    sel.onReadable(new AcceptorReadable());
    sel.onFree(new AcceptorFree());
    sel.setReactor(reactor);
    BaseHandler.setHandler(this, handler);
    sel.setReading(true);
    reactor.update(sel);
}
 
Example 10
Source File: DownstreamServer.java    From nassau with Apache License 2.0 5 votes vote down vote up
public static DownstreamServer open(UpstreamFactory upstream,
        InetSocketAddress address) throws IOException {
    ServerSocketChannel serverChannel = ServerSocketChannel.open();

    serverChannel.bind(address);
    serverChannel.configureBlocking(false);

    return new DownstreamServer(upstream, serverChannel);
}
 
Example 11
Source File: TestMessageIO.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static ServerSocketChannel createServer() throws IOException {
    // Create a server on a random port
    ServerSocketChannel server = ServerSocketChannel.open();
    server.bind(new InetSocketAddress("localhost", 0));
    server.configureBlocking(false);
    return server;
}
 
Example 12
Source File: SocketChannelConnectionAcceptor.java    From bt with Apache License 2.0 5 votes vote down vote up
/**
 * @return Local socket channel, used for accepting the incoming connections
 */
private ServerSocketChannel getServerChannel() throws IOException {
    if (serverChannel == null) {
        ServerSocketChannel _serverChannel = selector.provider().openServerSocketChannel();
        _serverChannel.bind(localAddress);
        _serverChannel.configureBlocking(true);
        serverChannel = _serverChannel;
        LOGGER.info("Opening server channel for incoming connections @ {}", localAddress);
    }
    return serverChannel;
}
 
Example 13
Source File: ServerTCPListener.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** @return Socket bound to EPICS_PVA_SERVER_PORT or unused port */
private static ServerSocketChannel createSocket() throws Exception
{
    ServerSocketChannel socket = ServerSocketChannel.open();
    socket.configureBlocking(true);
    socket.socket().setReuseAddress(true);
    try
    {
        socket.bind(new InetSocketAddress(PVASettings.EPICS_PVA_SERVER_PORT));
        return socket;
    }
    catch (BindException ex)
    {
        logger.log(Level.INFO, "TCP port " + PVASettings.EPICS_PVA_SERVER_PORT + " already in use, switching to automatically assigned port");
        final InetSocketAddress any = new InetSocketAddress(0);
        try
        {   // Must create new socket after bind() failed, cannot re-use
            socket = ServerSocketChannel.open();
            socket.configureBlocking(true);
            socket.socket().setReuseAddress(true);
            socket.bind(any);
            return socket;
        }
        catch (Exception e)
        {
            throw new Exception("Cannot bind to automatically assigned port " + any, e);
        }
    }
}
 
Example 14
Source File: TestBlockingNIO.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
@Test
public void server() throws IOException {
    // 1. 获取通道
    ServerSocketChannel ssChannel = ServerSocketChannel.open();

    FileChannel outChannel =
            FileChannel.open(
                    Paths.get("2.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);

    // 2. 绑定连接
    ssChannel.bind(new InetSocketAddress(9898));

    // 3. 获取客户端连接的通道
    SocketChannel sChannel = ssChannel.accept();

    // 4. 分配指定大小的缓冲区
    ByteBuffer buf = ByteBuffer.allocate(1024);

    // 5. 接收客户端的数据,并保存到本地
    while (sChannel.read(buf) != -1) {
        buf.flip();
        outChannel.write(buf);
        buf.clear();
    }

    // 6. 关闭通道
    sChannel.close();
    outChannel.close();
    ssChannel.close();
}
 
Example 15
Source File: TestBlockingNIO2.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
@Test
public void server() throws IOException {
    ServerSocketChannel ssChannel = ServerSocketChannel.open();

    FileChannel outChannel =
            FileChannel.open(
                    Paths.get("2.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);

    ssChannel.bind(new InetSocketAddress(9898));

    SocketChannel sChannel = ssChannel.accept();

    ByteBuffer buf = ByteBuffer.allocate(1024);

    while (sChannel.read(buf) != -1) {
        buf.flip();
        outChannel.write(buf);
        buf.clear();
    }

    // 发送反馈给客户端
    buf.put("服务端接收数据成功".getBytes());
    buf.flip();
    sChannel.write(buf);

    sChannel.close();
    outChannel.close();
    ssChannel.close();
}
 
Example 16
Source File: Io.java    From PlusDemo with Apache License 2.0 5 votes vote down vote up
private static void nio2() {
    try {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        SocketChannel socketChannel = serverSocketChannel.accept();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (socketChannel.read(byteBuffer) != -1) {
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            byteBuffer.clear();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 17
Source File: ServerSocket.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
   ServerSocketChannel server = ServerSocketChannel.open();
   server.bind(new InetSocketAddress("127.0.0.1", 5557));
   while (true) {
      SocketChannel client = server.accept();
      new Thread(new Client(client)).start();
   }
}
 
Example 18
Source File: ShellLaunchManager.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Registers the connection and initiates the listening socket.
 * @param project the project which is being run / debugged
 * @param debugger if true, the connection will pair with a debugger session.
 */
public ShellAgent openForProject(Project p, boolean debugger) throws IOException {
    ServerSocket ss;
    
    String encodedKey;
    boolean shouldInit = false;
    
    synchronized (this) {
        shouldInit = usedKeys.isEmpty();
        do {
            BigInteger key = BigInteger.probablePrime(64, keyGenerator);
            encodedKey = key.toString(Character.MAX_RADIX);
        } while (!usedKeys.add(encodedKey));
    }
    
    if (shouldInit) {
        init();
    }
    
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);
    SocketAddress local = new InetSocketAddress(
        // PENDING: choose something better for remote debugging!
        InetAddress.getLoopbackAddress(),
        0);
    ssc.bind(local);
    ssc.accept();
    ss = ssc.socket();
    LOG.log(Level.FINE, "Creating new server socket {0} for project: {1}", new Object[] {
        ss, p
    });
    ShellAgent agent = new ShellAgent(this, p, ss, encodedKey, debugger);
    synchronized (this) {
        registeredAgents.put(encodedKey, agent);
    }
    synchronized (requests) {
        servers.wakeup();
        requests.add(agent);
        
    }
    return agent;
}
 
Example 19
Source File: NioSslIntegrationTest.java    From Chronicle-Network with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldEncryptAndDecryptTraffic() throws Exception {
    final ExecutorService threadPool = Executors.newFixedThreadPool(2,
            new NamedThreadFactory("test"));

    final ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.bind(new InetSocketAddress("0.0.0.0", 13337));
    serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    serverChannel.configureBlocking(true);

    final SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(false);
    channel.connect(new InetSocketAddress("127.0.0.1", serverChannel.socket().getLocalPort()));

    try {

        final Client client = new Client(channel);

        final StateMachineProcessor clientProcessor = new StateMachineProcessor(channel, false,
                SSLContextLoader.getInitialisedContext(), client);

        final SocketChannel serverConnection = serverChannel.accept();
        serverConnection.configureBlocking(false);

        final Server server = new Server(serverConnection);
        final StateMachineProcessor serverProcessor = new StateMachineProcessor(serverConnection, true,
                SSLContextLoader.getInitialisedContext(), server);

        while (!(channel.finishConnect() && serverConnection.finishConnect())) {
            Thread.yield();
        }

        if (SEND_DATA_BEFORE_SSL_HANDSHAKE) {
            testDataConnection(channel, serverConnection);
        }

        threadPool.submit(clientProcessor);
        threadPool.submit(serverProcessor);

        client.waitForResponse(10, TimeUnit.SECONDS);
        serverProcessor.stop();
        clientProcessor.stop();
    } finally {
        Closeable.closeQuietly(channel, serverChannel);
    }

    threadPool.shutdown();
    assertTrue(threadPool.awaitTermination(10, TimeUnit.SECONDS));
}
 
Example 20
Source File: Acceptor.java    From philadelphia with Apache License 2.0 3 votes vote down vote up
static Acceptor open(InetSocketAddress address) throws IOException {
    ServerSocketChannel serverChannel = ServerSocketChannel.open();

    serverChannel.bind(address);

    return new Acceptor(serverChannel);
}