/** * Starts listening to slave connections. * * @throws Exception If fails. */ public void beginAccept() throws Exception { this.serverSocketChannel = ServerSocketChannel.open(); this.selector = RemotingUtil.openSelector(); this.serverSocketChannel.socket().setReuseAddress(true); this.serverSocketChannel.socket().bind(this.socketAddressListen); this.serverSocketChannel.configureBlocking(false); this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT); }
private void onChannelAcceptable(SelectionKey key) throws IOException { ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ); readKey.attach(key.attachment()); }
/** * Initiates the shuts down of the listener. */ public void shutdown() { shuttingDown = true; try { SocketAddress localAddress = serverSocket.getLocalAddress(); if (localAddress instanceof InetSocketAddress) { InetSocketAddress address = (InetSocketAddress) localAddress; Socket client = new Socket(address.getHostName(), address.getPort()); client.setSoTimeout(1000); // waking the acceptor loop should be quick new PingAgentProtocol().connect(client); } } catch (IOException e) { LOGGER.log(Level.FINE, "Failed to send Ping to wake acceptor loop", e); } try { serverSocket.close(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to close down TCP port",e); } }
/** * Binds TCP socket on the provided <code>port</code>. * * @throws IOException if any I/O error occurs. */ @Override public void bind() throws IOException { getJavaChannel().socket().bind( new InetSocketAddress(InetAddress.getLocalHost(), port)); getJavaChannel().configureBlocking(false); LOGGER.info("Bound TCP socket at port: {}", port); }
@Override public ServerSocket createServerSocket(int port) throws IOException { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(port)); return serverSocketChannel.socket(); }
public void serve(int port) throws IOException { ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(false); ServerSocket ss = serverChannel.socket(); InetSocketAddress address = new InetSocketAddress(port); ss.bind(address); Selector selector = Selector.open(); serverChannel.register(selector, SelectionKey.OP_ACCEPT); final ByteBuffer msg = ByteBuffer.wrap("Hi!\r\n".getBytes()); for (;;){ try { selector.select(); } catch (IOException ex) { ex.printStackTrace(); iterator.remove(); try { if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel client = server.accept(); client.configureBlocking(false); client.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ, msg.duplicate()); System.out.println( "Accepted connection from " + client); if (key.isWritable()) {
protected void start(boolean direct) throws Exception { selector=Selector.open(); ch=ServerSocketChannel.open(); ch.bind(new InetSocketAddress("0.0.0.0", 7500)); ch.configureBlocking(false); ch.register(selector, SelectionKey.OP_ACCEPT, null); System.out.println("-- server ready"); selector.select(); Set<SelectionKey> keys=selector.selectedKeys(); for(Iterator<SelectionKey> it=keys.iterator(); it.hasNext();) { SelectionKey key=it.next(); if(!key.isValid()) { it.remove(); continue; if(key.isAcceptable()) { SocketChannel client_ch=ch.accept(); if(client_ch != null) { // accept() may return null... System.out.printf("accepted connection from %s\n", client_ch.getRemoteAddress()); client_ch.configureBlocking(false); client_ch.register(selector, SelectionKey.OP_READ, create(SIZE, direct)); else if(key.isReadable()) { if(!handle((SocketChannel)key.channel(), (ByteBuffer)key.attachment())) { key.cancel();
public SocksProxy(int runningTime) throws IOException { ServerSocketChannel socks = ServerSocketChannel.open(); socks.socket().bind(new InetSocketAddress(8000)); socks.configureBlocking(false); Selector select = Selector.open(); socks.register(select, SelectionKey.OP_ACCEPT); select.select(5000); Set<SelectionKey> keys = select.selectedKeys(); for (SelectionKey k : keys) { if (!k.isValid()) continue; if (k.isAcceptable() && k.channel() == socks) { SocketChannel csock = socks.accept(); if (csock == null) continue; addClient(csock); csock.register(select, SelectionKey.OP_READ); } else if (k.isReadable()) { cl.client.close(); if (cl.remote != null) cl.remote.close(); k.cancel(); clients.remove(cl);
ListenTask(int port) throws IOException { this.port = port; this.ssc = ServerSocketChannel.open(); ssc.socket().setReuseAddress(true); ssc.socket().bind(new InetSocketAddress(port), LISTEN_BACKLOG); ssc.configureBlocking(false); endpoint = new EndPoint(NioSelectorScheduler.this,ssc); // if port is automatically assigned then retrieve actual value if(port == 0) { this.port = ssc.socket().getLocalPort(); }; }
System.out.println("Sender Start"); ServerSocketChannel ssChannel = ServerSocketChannel.open(); ssChannel.configureBlocking(true); int port = 12345; ssChannel.socket().bind(new InetSocketAddress(port)); SocketChannel sChannel = ssChannel.accept(); ObjectOutputStream(sChannel.socket().getOutputStream()); oos.writeObject(obj); oos.close();
@Test public void testInboundConnectionsCountInConnectionCreationMetric() throws Exception { int conns = 5; try (ServerSocketChannel ss = ServerSocketChannel.open()) { ss.bind(new InetSocketAddress(0)); InetSocketAddress serverAddress = (InetSocketAddress) ss.getLocalAddress(); for (int i = 0; i < conns; i++) { Thread sender = createSender(serverAddress, randomPayload(1)); sender.start(); SocketChannel channel = ss.accept(); channel.configureBlocking(false); selector.register(Integer.toString(i), channel); } } assertEquals((double) conns, getMetric("connection-creation-total").metricValue()); assertEquals((double) conns, getMetric("connection-count").metricValue()); }
boolean ok = false; try { accepted = channel.accept(); if (accepted != null) try { final SocketAddress localAddress = accepted.getLocalAddress(); int hash; if (localAddress instanceof InetSocketAddress) { final InetSocketAddress address = (InetSocketAddress) localAddress; hash = address.getAddress().hashCode() * 23 + address.getPort(); } else if (localAddress instanceof LocalSocketAddress) { hash = ((LocalSocketAddress) localAddress).getName().hashCode(); hash = localAddress.hashCode(); final SocketAddress remoteAddress = accepted.getRemoteAddress(); if (remoteAddress instanceof InetSocketAddress) { final InetSocketAddress address = (InetSocketAddress) remoteAddress; hash = (address.getAddress().hashCode() * 23 + address.getPort()) * 23 + hash; } else if (remoteAddress instanceof LocalSocketAddress) { hash = ((LocalSocketAddress) remoteAddress).getName().hashCode() * 23 + hash; hash = localAddress.hashCode() * 23 + hash;
@NotNull @Override public ServerSocketChannel channelFor(Selector selector) throws IOException { ServerSocketChannel myServerSocketChannel = selector.provider().openServerSocketChannel(); myServerSocketChannel.configureBlocking(false); int bindPort = -1; for (int port = firstTryPort; port <= lastTryPort; port++) { try { InetSocketAddress tryAddress = new InetSocketAddress(port); myServerSocketChannel.socket().bind(tryAddress); bindPort = tryAddress.getPort(); break; } catch (IOException e) { //try next port logger.debug("Could not bind to port {}, trying next port...", port); } } if (bindPort == -1) { logger.error(String.format( "No available ports in range [%d, %d] for the BitTorrent client!", firstTryPort, lastTryPort )); throw new IOException("No available port for the BitTorrent client!"); } return myServerSocketChannel; } }
@Override public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException { stopped = false; executor = Executors.newFixedThreadPool(maxConnections); final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); if (maxBufferSize > 0) { serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize); final int actualReceiveBufSize = serverSocketChannel.getOption(StandardSocketOptions.SO_RCVBUF); if (actualReceiveBufSize < maxBufferSize) { logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize + " bytes but could only set to " + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's " + "maximum receive buffer"); } } serverSocketChannel.socket().bind(new InetSocketAddress(nicAddress, port)); selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); }
public Listener() throws IOException { address = new InetSocketAddress(bindAddress, port); // Create a new server socket and set to non blocking mode acceptChannel = ServerSocketChannel.open(); acceptChannel.configureBlocking(false); // Bind the server socket to the local host and port bind(acceptChannel.socket(), address, backlogLength, conf, portRangeConfig); port = acceptChannel.socket().getLocalPort(); //Could be an ephemeral port // create a selector; selector= Selector.open(); readers = new Reader[readThreads]; for (int i = 0; i < readThreads; i++) { Reader reader = new Reader( "Socket Reader #" + (i + 1) + " for port " + port); readers[i] = reader; reader.start(); } // Register accepts on the server socket with the selector. acceptChannel.register(selector, SelectionKey.OP_ACCEPT); this.setName("IPC Server listener on " + port); this.setDaemon(true); }
SystemTimer tmp_timer = null; if (isSelector()) { tmp_s = Selector.open(); // no longer catch ex to fix bug 36907 "Selector thread pooling can not be used with client/server SSL. The selector can be disabled by setting max-threads=0."); ServerSocketChannel channel = ServerSocketChannel.open(); this.serverSock = channel.socket(); this.serverSock.setReuseAddress(true); this.serverSock.setReceiveBufferSize(socketBufferSize); this.serverSock.bind(new InetSocketAddress(getBindAddress(), port), backLog); break; } catch (SocketException b) {
Selector selector = Selector.open(); int[] ports = {4000,4001,6000}; for (int port : ports) { ServerSocketChannel server = ServerSocketChannel.open(); server.configureBlocking(false); server.socket().bind(new InetSocketAddress(port)); // we are only interested when accept evens occur on this socket server.register(selector, SelectionKey.OP_ACCEPT); } while (selector.isOpen()) { selector.select(); Set readyKeys = selector.selectedKeys(); Iterator iterator = readyKeys.iterator(); while (iterator.hasNext()) { SelectionKey key = (SelectionKey) iterator.next(); if (key.isAcceptable()) { SocketChannel client = server.accept(); Socket socket = client.socket(); // create new thread to deal with connection (closing both socket and client when done) } } } // tidy up selector and channels
default ServerSocketChannel createServerSocketChannel(String service_name, int port) throws IOException { return createServerSocketChannel(service_name).bind(new InetSocketAddress(port)); }
private void openSocket() throws IOException { U.notNull(net.protocol(), "protocol"); U.notNull(net.helperClass(), "helperClass"); String blockingInfo = net.blockingAccept() ? "blocking" : "non-blocking"; Log.debug("Initializing server", "address", net.address(), "port", net.port(), "sync", net.syncBufs(), "accept", blockingInfo); serverSocketChannel = ServerSocketChannel.open(); if ((serverSocketChannel.isOpen()) && (selector.isOpen())) { serverSocketChannel.configureBlocking(net.blockingAccept()); ServerSocket socket = serverSocketChannel.socket(); Log.info("!Starting server", "!address", net.address(), "!port", net.port(), "I/O workers", net.workers(), "sync", net.syncBufs(), "accept", blockingInfo); InetSocketAddress addr = new InetSocketAddress(net.address(), net.port()); socket.setReceiveBufferSize(16 * 1024); socket.setReuseAddress(true); socket.bind(addr, MAX_PENDING_CONNECTIONS); Log.debug("Opened server socket", "address", addr); if (!net.blockingAccept()) { Log.debug("Registering accept selector"); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } initWorkers(); } else { throw U.rte("Cannot open socket!"); } }
public void run() { while (!ss.socket().isClosed()) { try { selector.select(1000); Set<SelectionKey> selected; synchronized (this) { selected = selector.selectedKeys(); Collections.shuffle(selectedList); for (SelectionKey k : selectedList) { if ((k.readyOps() & SelectionKey.OP_ACCEPT) != 0) { SocketChannel sc = ((ServerSocketChannel) k .channel()).accept(); InetAddress ia = sc.socket().getInetAddress(); int cnxncount = getClientCnxnCount(ia); if (maxClientCnxns > 0 && cnxncount >= maxClientCnxns){ LOG.warn("Too many connections from " + ia + " - max is " + maxClientCnxns ); sc.close(); } else { LOG.info("Accepted socket connection from " + sc.socket().getRemoteSocketAddress()); sc.configureBlocking(false); SelectionKey sk = sc.register(selector, SelectionKey.OP_READ); NIOServerCnxn cnxn = createConnection(sc, sk); sk.attach(cnxn); addCnxn(cnxn);