java.nio.channels.ServerSocketChannel Java Examples

The following examples show how to use java.nio.channels.ServerSocketChannel. 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: KeepAliveSockets.java    From openjdk-jdk8u-backup with 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 #2
Source File: KeepAliveSockets.java    From jdk8u-dev-jdk with 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 #3
Source File: ShutdownInput.java    From jdk8u_jdk with 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 #4
Source File: NetServer.java    From nullpomino with 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 #5
Source File: NonBlockingServerWithOffLoopTasks.java    From tls-channel with 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 #6
Source File: ShutdownInput.java    From jdk8u-jdk with 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 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 #8
Source File: GfxdTServerSocket.java    From gemfirexd-oss with 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 #9
Source File: ShutdownInput.java    From hottub with 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 #10
Source File: NioServer.java    From light-task-scheduler with 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 #11
Source File: GfxdTServerSocket.java    From gemfirexd-oss with 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 #12
Source File: SimpleRpcNioSelector.java    From hasting with 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 #13
Source File: ShutdownInput.java    From jdk8u60 with 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 #14
Source File: KeepAliveSockets.java    From openjdk-8 with 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 #15
Source File: SocketChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests SocketChannel#read(ByteBuffer[], int, int) when remote server
 *        closed
 */
public void test_socketChannel_read_ByteBufferII_remoteClosed()
        throws Exception {
    // regression 1 for HARMONY-549
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(null);
    SocketChannel sc = SocketChannel.open();
    sc.connect(ssc.socket().getLocalSocketAddress());
    ssc.accept().close();
    ByteBuffer[] buf = { ByteBuffer.allocate(10) };
    assertEquals(-1, sc.read(buf, 0, 1));
    ssc.close();
    sc.close();
}
 
Example #16
Source File: SocketTunnel.java    From AgentX with Apache License 2.0 5 votes vote down vote up
public void restart() throws IOException {
    server.close();
    selector.selectNow();
    server = ServerSocketChannel.open();
    server.configureBlocking(false);
    server.socket().setReuseAddress(true);
    server.socket().bind(srcAddr);
    server.register(selector, SelectionKey.OP_ACCEPT);
    bridge.clear();
}
 
Example #17
Source File: TcpAcceptor.java    From netcrusher-java with Apache License 2.0 5 votes vote down vote up
TcpAcceptor(
    TcpCrusher crusher,
    NioReactor reactor,
    InetSocketAddress bindAddress,
    InetSocketAddress connectAddress,
    InetSocketAddress bindBeforeConnectAddress,
    TcpCrusherSocketOptions socketOptions,
    TcpFilters filters,
    BufferOptions bufferOptions) throws IOException
{
    this.crusher = crusher;
    this.bindAddress = bindAddress;
    this.connectAddress = connectAddress;
    this.bindBeforeConnectAddress = bindBeforeConnectAddress;
    this.socketOptions = socketOptions;
    this.reactor = reactor;
    this.bufferOptions = bufferOptions;
    this.filters = filters;
    this.totalAccepted = new AtomicInteger(0);

    this.serverSocketChannel = ServerSocketChannel.open();
    this.serverSocketChannel.configureBlocking(false);
    this.serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);

    if (socketOptions.getBacklog() > 0) {
        this.serverSocketChannel.bind(bindAddress, socketOptions.getBacklog());
    } else {
        this.serverSocketChannel.bind(bindAddress);
    }

    this.serverSelectionKey = reactor.getSelector()
        .register(serverSocketChannel, 0, (selectionKey) -> this.accept());

    this.state = new State(State.FROZEN);
}
 
Example #18
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 #19
Source File: Server.java    From Bats with 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 #20
Source File: SendUrgentData.java    From TencentKona-8 with 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 #21
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 #22
Source File: NettyAddressInUseTest.java    From sctp with 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 #23
Source File: Main.java    From netty.book.kor with 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 #24
Source File: RpcNioAcceptor.java    From hasting with 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 #25
Source File: SocketServer.java    From netbeans with 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 #26
Source File: SelectorThread.java    From L2jBrasil with 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 #27
Source File: SendUrgentData.java    From openjdk-jdk9 with 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 #28
Source File: HttpClientTest.java    From reactor-netty with 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 #29
Source File: SendUrgentData.java    From jdk8u-dev-jdk with 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 #30
Source File: NioServer.java    From Geisha with 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));
    }
}