Java Code Examples for java.nio.channels.ServerSocketChannel

The following examples show how to use java.nio.channels.ServerSocketChannel. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
public static void main(String[] args) throws Exception {

        boolean keepAlive = false;
        String prop = System.getProperty("com.sun.CORBA.transport.enableTcpKeepAlive");
        if (prop != null)
            keepAlive = !"false".equalsIgnoreCase(prop);

        DefaultSocketFactoryImpl sfImpl = new DefaultSocketFactoryImpl();
        ORBImpl orb = new ORBImpl();
        orb.set_parameters(null);
        sfImpl.setORB(orb);

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(0));

        InetSocketAddress isa = new InetSocketAddress("localhost", ssc.socket().getLocalPort());
        Socket s = sfImpl.createSocket("ignore", isa);
        System.out.println("Received factory socket" + s);
        if (keepAlive != s.getKeepAlive())
            throw new RuntimeException("KeepAlive value not honoured in CORBA socket");
    }
 
Example 2
Source Project: nullpomino   Source File: NetServer.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Initialize the selector
 * @return The selector we'll be monitoring
 * @throws IOException When the selector can't be created (Usually when the port is already in use)
 */
private Selector initSelector() throws IOException {
	// Create a new selector
	Selector socketSelector = SelectorProvider.provider().openSelector();

	// Create a new non-blocking server socket channel
	this.serverChannel = ServerSocketChannel.open();
	serverChannel.configureBlocking(false);

	// Bind the server socket to the specified address and port
	InetSocketAddress isa = new InetSocketAddress(this.port);
	serverChannel.socket().bind(isa);

	// Register the server socket channel, indicating an interest in
	// accepting new connections
	serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT);

	log.info("Listening on port " + this.port + "...");

	return socketSelector;
}
 
Example 3
Source Project: tls-channel   Source File: NonBlockingServerWithOffLoopTasks.java    License: MIT License 6 votes vote down vote up
private static void handleNewConnection(
    SSLContext sslContext, Selector selector, ServerSocketChannel serverChannel)
    throws IOException {
  // accept new connection
  SocketChannel rawChannel = serverChannel.accept();
  rawChannel.configureBlocking(false);

  // wrap raw channel in TlsChannel
  TlsChannel tlsChannel =
      ServerTlsChannel.newBuilder(rawChannel, sslContext).withRunTasks(false).build();

  /*
   * Wrap raw channel with a TlsChannel. Note that the raw channel is registered in the selector
   * and the TlsChannel put as an attachment register the channel for reading, because TLS
   * connections are initiated by clients.
   */
  SelectionKey newKey = rawChannel.register(selector, SelectionKey.OP_READ);
  newKey.attach(tlsChannel);
}
 
Example 4
Source Project: jdk8u-jdk   Source File: ShutdownInput.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    InetAddress iaddr = InetAddress.getLocalHost();

    try ( ServerSocket ss = new ServerSocket(0);
          Socket s1 = new Socket(iaddr, ss.getLocalPort());
          Socket s2 = ss.accept() ) {

        test(s1, s2, "Testing NET");
    }

    // check the NIO socket adapter
    try (ServerSocketChannel sc = ServerSocketChannel.open().bind(null);
         SocketChannel s1 = SocketChannel.open(
                 new InetSocketAddress(iaddr, sc.socket().getLocalPort()));
         SocketChannel s2 = sc.accept() ) {

        test(s1.socket(), s2.socket(), "Testing NIO");
    }

    if (failed) {
        throw new RuntimeException("Failed: check output");
    }
}
 
Example 5
Source Project: new-bull   Source File: ReactorEchoServerV2.java    License: 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 6
Source Project: jdk8u_jdk   Source File: ShutdownInput.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    InetAddress iaddr = InetAddress.getLocalHost();

    try ( ServerSocket ss = new ServerSocket(0);
          Socket s1 = new Socket(iaddr, ss.getLocalPort());
          Socket s2 = ss.accept() ) {

        test(s1, s2, "Testing NET");
    }

    // check the NIO socket adapter
    try (ServerSocketChannel sc = ServerSocketChannel.open().bind(null);
         SocketChannel s1 = SocketChannel.open(
                 new InetSocketAddress(iaddr, sc.socket().getLocalPort()));
         SocketChannel s2 = sc.accept() ) {

        test(s1.socket(), s2.socket(), "Testing NIO");
    }

    if (failed) {
        throw new RuntimeException("Failed: check output");
    }
}
 
Example 7
Source Project: gemfirexd-oss   Source File: GfxdTServerSocket.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a port listening server socket
 */
public GfxdTServerSocket(InetSocketAddress bindAddress, boolean blocking,
    boolean clientBlocking, SocketParameters params)
    throws TTransportException {
  this.clientBlocking = clientBlocking;
  this.socketParams = params;
  try {
    // Make server socket
    this.serverSockChannel = ServerSocketChannel.open();
    this.serverSockChannel.configureBlocking(blocking);
    ServerSocket socket = this.serverSockChannel.socket();
    // Prevent 2MSL delay problem on server restarts
    socket.setReuseAddress(true);
    // Bind to listening port
    socket.bind(bindAddress);
  } catch (IOException ioe) {
    throw new TTransportException(TTransportException.NOT_OPEN,
        "Could not bind to host:port " + bindAddress.toString(), ioe);
  }
}
 
Example 8
Source Project: hottub   Source File: ShutdownInput.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    InetAddress iaddr = InetAddress.getLocalHost();

    try ( ServerSocket ss = new ServerSocket(0);
          Socket s1 = new Socket(iaddr, ss.getLocalPort());
          Socket s2 = ss.accept() ) {

        test(s1, s2, "Testing NET");
    }

    // check the NIO socket adapter
    try (ServerSocketChannel sc = ServerSocketChannel.open().bind(null);
         SocketChannel s1 = SocketChannel.open(
                 new InetSocketAddress(iaddr, sc.socket().getLocalPort()));
         SocketChannel s2 = sc.accept() ) {

        test(s1.socket(), s2.socket(), "Testing NIO");
    }

    if (failed) {
        throw new RuntimeException("Failed: check output");
    }
}
 
Example 9
Source Project: light-task-scheduler   Source File: NioServer.java    License: Apache License 2.0 6 votes vote down vote up
private void init() {

        ServerSocketChannel socketChannel = processor.javaChannel();

        ServerSocket javaSocket = socketChannel.socket();

        try {
            if (serverConfig.getReceiveBufferSize() != null) {
                javaSocket.setReceiveBufferSize(serverConfig.getReceiveBufferSize());
            }
            if (serverConfig.getReuseAddress() != null) {
                javaSocket.setReuseAddress(serverConfig.getReuseAddress());
            }
        } catch (SocketException e) {
            throw new NioException("config channel error:" + e.getMessage(), e);
        }
    }
 
Example 10
Source Project: gemfirexd-oss   Source File: GfxdTServerSocket.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a port listening server socket
 */
public GfxdTServerSocket(InetSocketAddress bindAddress, boolean blocking,
    boolean clientBlocking, SocketParameters params)
    throws TTransportException {
  this.clientBlocking = clientBlocking;
  this.socketParams = params;
  try {
    // Make server socket
    this.serverSockChannel = ServerSocketChannel.open();
    this.serverSockChannel.configureBlocking(blocking);
    ServerSocket socket = this.serverSockChannel.socket();
    // Prevent 2MSL delay problem on server restarts
    socket.setReuseAddress(true);
    // Bind to listening port
    socket.bind(bindAddress);
  } catch (IOException ioe) {
    throw new TTransportException(TTransportException.NOT_OPEN,
        "Could not bind to host:port " + bindAddress.toString(), ioe);
  }
}
 
Example 11
Source Project: hasting   Source File: SimpleRpcNioSelector.java    License: MIT License 6 votes vote down vote up
private void handSelectionKeyException(final SelectionKey selectionKey,Exception e){
	SelectableChannel channel = selectionKey.channel();
	if(channel instanceof ServerSocketChannel){
		RpcNioAcceptor acceptor = acceptorCache.get(channel);
		if(acceptor!=null){
			logger.error("acceptor "+acceptor.getHost()+":"+acceptor.getPort()+" selection error "+e.getClass()+" "+e.getMessage()+" start to shutdown");
			this.fireNetListeners(acceptor, e);
			acceptor.stopService();
		}
	}else{
		RpcNioConnector connector = connectorCache.get(channel);
		if(connector!=null){
			logger.error("connector "+connector.getHost()+":"+connector.getPort()+" selection error "+e.getClass()+" "+e.getMessage()+" start to shutdown");
			this.fireNetListeners(connector, e);
			connector.stopService();
		}
	}
	this.logState();
}
 
Example 12
Source Project: jdk8u60   Source File: ShutdownInput.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    InetAddress iaddr = InetAddress.getLocalHost();

    try ( ServerSocket ss = new ServerSocket(0);
          Socket s1 = new Socket(iaddr, ss.getLocalPort());
          Socket s2 = ss.accept() ) {

        test(s1, s2, "Testing NET");
    }

    // check the NIO socket adapter
    try (ServerSocketChannel sc = ServerSocketChannel.open().bind(null);
         SocketChannel s1 = SocketChannel.open(
                 new InetSocketAddress(iaddr, sc.socket().getLocalPort()));
         SocketChannel s2 = sc.accept() ) {

        test(s1.socket(), s2.socket(), "Testing NIO");
    }

    if (failed) {
        throw new RuntimeException("Failed: check output");
    }
}
 
Example 13
Source Project: openjdk-8   Source File: KeepAliveSockets.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        boolean keepAlive = false;
        String prop = System.getProperty("com.sun.CORBA.transport.enableTcpKeepAlive");
        if (prop != null)
            keepAlive = !"false".equalsIgnoreCase(prop);

        DefaultSocketFactoryImpl sfImpl = new DefaultSocketFactoryImpl();
        ORBImpl orb = new ORBImpl();
        orb.set_parameters(null);
        sfImpl.setORB(orb);

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(0));

        InetSocketAddress isa = new InetSocketAddress("localhost", ssc.socket().getLocalPort());
        Socket s = sfImpl.createSocket("ignore", isa);
        System.out.println("Received factory socket" + s);
        if (keepAlive != s.getKeepAlive())
            throw new RuntimeException("KeepAlive value not honoured in CORBA socket");
    }
 
Example 14
public static void main(String[] args) throws Exception {

        boolean keepAlive = false;
        String prop = System.getProperty("com.sun.CORBA.transport.enableTcpKeepAlive");
        if (prop != null)
            keepAlive = !"false".equalsIgnoreCase(prop);

        DefaultSocketFactoryImpl sfImpl = new DefaultSocketFactoryImpl();
        ORBImpl orb = new ORBImpl();
        orb.set_parameters(null);
        sfImpl.setORB(orb);

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(0));

        InetSocketAddress isa = new InetSocketAddress("localhost", ssc.socket().getLocalPort());
        Socket s = sfImpl.createSocket("ignore", isa);
        System.out.println("Received factory socket" + s);
        if (keepAlive != s.getKeepAlive())
            throw new RuntimeException("KeepAlive value not honoured in CORBA socket");
    }
 
Example 15
Source Project: reactor-netty   Source File: HttpClientTest.java    License: Apache License 2.0 5 votes vote down vote up
private ConnectionResetByPeerServer(int port) {
	super(1);
	this.port = port;
	try {
		server = ServerSocketChannel.open();
	}
	catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 16
Source Project: unidbg   Source File: AbstractDebugServer.java    License: Apache License 2.0 5 votes vote down vote up
private void onSelectAccept(SelectionKey key) throws IOException {
    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
    SocketChannel sc = ssc.accept();
    if (sc != null) {
        closeConnection = false;
        pendingWrites.clear();
        input.clear();
        sc.configureBlocking(false);
        sc.register(key.selector(), SelectionKey.OP_READ);
        socketChannel = sc;
        enableNewConnections(false);
        onDebuggerConnected();
    }
}
 
Example 17
/**
 * Start the server and begin accepting incoming connections.
 *
 */
@Override
public void startProcessing() {
	try{
		this_mon.enter();

   if( !isRunning() ) {
     try {
       server_channel = ServerSocketChannel.open();

       server_channel.socket().setReuseAddress( true );
       if( receive_buffer_size > 0 )  server_channel.socket().setReceiveBufferSize( receive_buffer_size );

       server_channel.socket().bind( bind_address, 1024 );

       if (Logger.isEnabled()) 	Logger.log(new LogEvent(LOGID, "TCP incoming server socket "	+ bind_address));

       AEThread accept_thread = new AEThread( "VServerSelector:port" + bind_address.getPort() ) {
         @Override
         public void runSupport() {
           accept_loop();
         }
       };
       accept_thread.setDaemon( true );
       accept_thread.start();
     }
     catch( Throwable t ) {
     	Debug.out( t );
     	Logger.log(new LogAlert(LogAlert.UNREPEATABLE,	"ERROR, unable to bind TCP incoming server socket to " +bind_address.getPort(), t));
     }

     last_accept_time = SystemTime.getCurrentTime();  //init to now
   }
	}finally{

		this_mon.exit();
	}
}
 
Example 18
Source Project: Bats   Source File: Server.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientListener getClientConnection(SocketChannel sc, ServerSocketChannel ssc)
{
  ClientListener client;
  if (authToken == null) {
    client = new UnidentifiedClient();
  } else {
    AuthClient authClient = new AuthClient();
    authClient.setToken(authToken);
    client = authClient;
  }
  return client;
}
 
Example 19
Source Project: hasting   Source File: RpcNioAcceptor.java    License: MIT License 5 votes vote down vote up
public RpcNioAcceptor(AbstractRpcNioSelector selector){
	try {
		serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.configureBlocking(false);
		this.selector = selector;
	} catch (IOException e) {
		this.handleNetException(e);
	}
}
 
Example 20
Source Project: swim   Source File: TlsService.java    License: Apache License 2.0 5 votes vote down vote up
TlsService(Station station, InetSocketAddress localAddress,
           ServerSocketChannel serverChannel, IpService service,
           IpSettings ipSettings) {
  this.station = station;
  this.localAddress = localAddress;
  this.serverChannel = serverChannel;
  this.service = service;
  this.ipSettings = ipSettings;
}
 
Example 21
Source Project: netty.book.kor   Source File: Main.java    License: MIT License 5 votes vote down vote up
private void acceptOP(SelectionKey key, Selector selector) throws IOException {

        ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
        SocketChannel socketChannel = serverChannel.accept();
        socketChannel.configureBlocking(false);

        System.out.println("Incoming connection from: " + socketChannel.getRemoteAddress());

        // write an welcome message
        socketChannel.write(ByteBuffer.wrap("Hello!\n".getBytes("UTF-8")));

        // register channel with selector for further I/O
        keepDataTrack.put(socketChannel, new ArrayList<byte[]>());
        socketChannel.register(selector, SelectionKey.OP_READ);
    }
 
Example 22
Source Project: PlusDemo   Source File: Io.java    License: 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 23
Source Project: j2objc   Source File: ServerSocketChannelTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @tests ServerSocketChannel#socket().getSoTimeout()
 */
public void test_accept_SOTIMEOUT() throws IOException {
    // Regression test for Harmony-707
    // The timeout actually used may be different from the one set due to
    // rounding by the Linux Kernel (see sock_set_timeout() in net/core/sock.c).
    // getSoTimeout() can return a different value from the one set with
    // setSoTimeout(). Consequently we do not check for equality with what was
    // set.

    ServerSocketChannel sc = ServerSocketChannel.open();
    try {
        sc.socket().bind(null);

        // Non blocking mode, accept() will return NULL since there are no pending connections.
        sc.configureBlocking(false);

        ServerSocket ss = sc.socket();

        int defaultTimeout = ss.getSoTimeout();
        assertEquals(0, defaultTimeout);
        // The timeout value is unimportant, providing it is large enough to be accepted
        // by the Kernel as distinct from the default.
        final int SO_TIMEOUT = 200;
        ss.setSoTimeout(SO_TIMEOUT);
        int nonDefaultTimeout = ss.getSoTimeout();
        assertTrue(nonDefaultTimeout != defaultTimeout);

        SocketChannel client = sc.accept();
        assertNull(client);
        // Confirm the timeout was unchanged.
        assertEquals(nonDefaultTimeout, ss.getSoTimeout());
    } finally {
        sc.close();
    }
}
 
Example 24
Source Project: javaide   Source File: MonitorThread.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Opens (or reopens) the "debug selected" port and listen for connections.
 * @return true if the port was opened successfully.
 * @throws IOException
 */
private boolean reopenDebugSelectedPort() throws IOException {

    Log.d("ddms", "reopen debug-selected port: " + mNewDebugSelectedPort);
    if (mDebugSelectedChan != null) {
        mDebugSelectedChan.close();
    }

    mDebugSelectedChan = ServerSocketChannel.open();
    mDebugSelectedChan.configureBlocking(false); // required for Selector

    InetSocketAddress addr = new InetSocketAddress(
            InetAddress.getByName("localhost"), //$NON-NLS-1$
            mNewDebugSelectedPort);
    mDebugSelectedChan.socket().setReuseAddress(true); // enable SO_REUSEADDR

    try {
        mDebugSelectedChan.socket().bind(addr);
        if (mSelectedClient != null) {
            mSelectedClient.update(Client.CHANGE_PORT);
        }

        mDebugSelectedChan.register(mSelector, SelectionKey.OP_ACCEPT, this);

        return true;
    } catch (java.net.BindException e) {
        displayDebugSelectedBindError(mNewDebugSelectedPort);

        // do not attempt to reopen it.
        mDebugSelectedChan = null;
        mNewDebugSelectedPort = -1;

        return false;
    }
}
 
Example 25
Source Project: code   Source File: NIOServer.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    // 1、创建选择器
    Selector selector = Selector.open();
    // 2、将通道注册到选择器上
    ServerSocketChannel ssChannel = ServerSocketChannel.open();
    // 设置非阻塞
    ssChannel.configureBlocking(false);
    ssChannel.register(selector, SelectionKey.OP_ACCEPT);
    // 3、监听事件
    ServerSocket serverSocket = ssChannel.socket();
    serverSocket.bind(new InetSocketAddress("127.0.0.1", 8080));

    while (true) {
        selector.select();
        Set<SelectionKey> keys = selector.selectedKeys();
        Iterator<SelectionKey> keyIterator = keys.iterator();
        // 5、事件循环
        while (keyIterator.hasNext()) {
            SelectionKey key = keyIterator.next();
            // 4、获取到达的事件
            if (key.isAcceptable()) {
                ServerSocketChannel ssChannel1 = (ServerSocketChannel) key.channel();
                // 服务器会为每个新连接创建一个 SocketChannel
                SocketChannel socketChannel = ssChannel1.accept();
                socketChannel.configureBlocking(false);
                // 这个新连接主要用于从客户端读取数据
                socketChannel.register(selector, SelectionKey.OP_READ);
            } else if (key.isReadable()) {
                SocketChannel sChannel = (SocketChannel) key.channel();
                System.out.println(readDataFromSocketChannel(sChannel));
                sChannel.close();
            }
            keyIterator.remove();
        }

    }

}
 
Example 26
Source Project: nifi   Source File: SocketChannelDispatcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int getPort() {
    // Return the port for the key listening for accepts
    for(SelectionKey key : selector.keys()){
        if (key.isValid()) {
            final Channel channel = key.channel();
            if (channel instanceof  ServerSocketChannel) {
                return ((ServerSocketChannel)channel).socket().getLocalPort();
            }
        }
    }
    return 0;
}
 
Example 27
Source Project: j2objc   Source File: SocketChannelTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Regression test for Harmony-1947.
 */
public void test_finishConnect() throws Exception {
    SocketAddress address = new InetSocketAddress("localhost", 0);

    ServerSocketChannel theServerChannel = ServerSocketChannel.open();
    ServerSocket serversocket = theServerChannel.socket();
    serversocket.setReuseAddress(true);
    // Bind the socket
    theServerChannel.socket().bind(address);

    boolean doneNonBlockingConnect = false;
    // Loop so that we make sure we're definitely testing finishConnect()
    while (!doneNonBlockingConnect) {
        channel1 = SocketChannel.open();

        // Set the SocketChannel to non-blocking so that connect(..) does
        // not block
        channel1.configureBlocking(false);
        boolean connected = channel1.connect(new InetSocketAddress("localhost",serversocket.getLocalPort()));
        if (!connected) {
            // Now set the SocketChannel back to blocking so that
            // finishConnect() blocks.
            channel1.configureBlocking(true);
            doneNonBlockingConnect = channel1.finishConnect();
        }
        if (doneNonBlockingConnect) {
            tryFinish();
        }
        channel1.close();
    }
    if (!serversocket.isClosed()) {
        serversocket.close();
    }
}
 
Example 28
Source Project: AgentX   Source File: SocketTunnel.java    License: Apache License 2.0 5 votes vote down vote up
public void startup() throws IOException {
    selector = Selector.open();
    server = ServerSocketChannel.open();
    server.configureBlocking(false);
    server.socket().setReuseAddress(true);
    server.socket().bind(srcAddr);
    server.register(selector, SelectionKey.OP_ACCEPT);
    new Thread(this).start();
}
 
Example 29
Source Project: sctp   Source File: AddressInUseTest.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private void doInitSocketServerTcp() throws IOException {
	dirtyServerTcp = ServerSocketChannel.open();
	dirtyServerTcp.configureBlocking(false);

	// Bind the server socket to the specified address and port
	InetSocketAddress isa = new InetSocketAddress(CLIENT_HOST, CLIENT_PORT);
	dirtyServerTcp.bind(isa);
}
 
Example 30
@Test(expected = BindException.class)
public void bindMultiTimes() throws InterruptedException, IOException {
    int port = 11911;
    List<ServerSocketChannel> serverSockets = new ArrayList<>(2);
    for (int i = 0; i < 2; i++) {
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSockets.add(serverSocket);
        serverSocket.socket().bind(new InetSocketAddress(port));
    }
    Thread.sleep(10 * 1000);
    System.out.println("done.");
}
 
Example 31
Source Project: circus-train   Source File: ServerSocketRule.java    License: Apache License 2.0 5 votes vote down vote up
public ServerSocketRule() {
  try {
    serverSocketChannel = (ServerSocketChannel) ServerSocketChannel
        .open()
        .bind(new InetSocketAddress(0))
        .configureBlocking(false);
    address = (InetSocketAddress) serverSocketChannel.getLocalAddress();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 32
Source Project: Geisha   Source File: NioServer.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void start() throws Exception {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.socket().bind(new InetSocketAddress(port));
    serverSocketChannel.configureBlocking(false);

    selector = Selector.open();
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    while (true) {
        selector.select(); // 此处的select方法是阻塞的
        // 对所有的key做一次遍历,由key本身判断此事件是否与自己有关
        selector.selectedKeys().forEach((this::handleKey));
    }
}
 
Example 33
Source Project: openjdk-jdk9   Source File: SendUrgentData.java    License: GNU General Public License v2.0 5 votes vote down vote up
private ServerSocketChannelThread(String name) {
    super(name);
    try {
        ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress((0)));
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 34
Source Project: L2jBrasil   Source File: SelectorThread.java    License: GNU General Public License v3.0 5 votes vote down vote up
public final void openServerSocket(InetAddress address, int tcpPort) throws IOException
{
    ServerSocketChannel selectable = ServerSocketChannel.open();
    selectable.configureBlocking(false);

    ServerSocket ss = selectable.socket();
    
    if (address == null)
        ss.bind(new InetSocketAddress(tcpPort));
    else
        ss.bind(new InetSocketAddress(address, tcpPort));
    
    selectable.register(_selector, SelectionKey.OP_ACCEPT);
}
 
Example 35
Source Project: netbeans   Source File: SocketServer.java    License: Apache License 2.0 5 votes vote down vote up
private void acceptConnection( SelectionKey key ) throws IOException {
    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

    SocketChannel socketChannel = serverSocketChannel.accept();
    socketChannel.configureBlocking(false);
    socketChannel.register(getSelector(), SelectionKey.OP_READ);
    initWriteQueue( socketChannel.keyFor(getSelector()));
}
 
Example 36
Source Project: jdk8u-dev-jdk   Source File: SendUrgentData.java    License: GNU General Public License v2.0 5 votes vote down vote up
private ServerSocketChannelThread(String name) {
    super(name);
    try {
        ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress((0)));
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 37
private void doInitSocketServerTcp() throws IOException {
    dirtyServerTcp = ServerSocketChannel.open();
    dirtyServerTcp.configureBlocking(false);

    // Bind the server socket to the specified address and port
    InetSocketAddress isa = new InetSocketAddress(CLIENT_HOST, CLIENT_PORT);
    dirtyServerTcp.bind(isa);
}
 
Example 38
Source Project: bt   Source File: SocketChannelConnectionAcceptor.java    License: 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 39
Source Project: TencentKona-8   Source File: SendUrgentData.java    License: GNU General Public License v2.0 5 votes vote down vote up
private ServerSocketChannelThread(String name) {
    super(name);
    try {
        ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress((0)));
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 40
Source Project: cosmic   Source File: NioServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void init() throws IOException {
    _selector = SelectorProvider.provider().openSelector();

    _serverSocket = ServerSocketChannel.open();
    _serverSocket.configureBlocking(false);

    _localAddr = new InetSocketAddress(_port);
    _serverSocket.socket().bind(_localAddr);

    _serverSocket.register(_selector, SelectionKey.OP_ACCEPT, null);

    s_logger.info("NioConnection started and listening on " + _localAddr.toString());
}