Search in sources :

Example 36 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project nifi by apache.

the class ChannelListener method addServerSocket.

/**
 * 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);
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 37 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project TeeTime by teetime-framework.

the class AbstractTcpReader method run.

@Override
public final void run() {
    ServerSocketChannel serversocket = null;
    try {
        serversocket = ServerSocketChannel.open();
        serversocket.socket().bind(new InetSocketAddress(this.port));
        if (logger.isDebugEnabled()) {
            logger.debug("Listening on port " + this.port);
        }
        final SocketChannel socketChannel = serversocket.accept();
        try {
            final ByteBuffer buffer = ByteBuffer.allocateDirect(bufferCapacity);
            while (socketChannel.read(buffer) != -1 && !terminated) {
                process(buffer);
            }
        } finally {
            socketChannel.close();
        }
    } catch (final IOException ex) {
        logger.error("Error while reading.", ex);
    } finally {
        if (null != serversocket) {
            try {
                serversocket.close();
            } catch (final IOException e) {
                logger.debug("Failed to close TCP connection.", e);
            }
        }
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 38 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project pancm_project by xuwujing.

the class socketTest method serve1.

/**
 * socket 实现非阻塞 I/O
 * @param port
 * @throws IOException
 */
public void serve1(int port) throws IOException {
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);
    ServerSocket ssocket = serverChannel.socket();
    InetSocketAddress address = new InetSocketAddress(port);
    ssocket.bind(address);
    // 打开Selector来处理Channel
    Selector selector = Selector.open();
    // 将ServerSocket 注册到Selector以接受连接
    serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    final ByteBuffer msg = ByteBuffer.wrap("Hi!\r\n".getBytes());
    for (; ; ) {
        try {
            // 等待需要处理的新事件; 阻 塞 将一直持续到下一个传入事件
            selector.select();
        } catch (IOException ex) {
            ex.printStackTrace();
            break;
        }
        // 获取所有接收事件的Selection-Key实例
        Set<SelectionKey> readyKeys = selector.selectedKeys();
        Iterator<SelectionKey> iterator = readyKeys.iterator();
        while (iterator.hasNext()) {
            SelectionKey key = iterator.next();
            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()) {
                    SocketChannel client = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    // 将数据写到已连接的客户端
                    while (buffer.hasRemaining()) {
                        if (client.write(buffer) == 0) {
                            break;
                        }
                    }
                    client.close();
                }
            } catch (IOException ex) {
                key.cancel();
                try {
                    key.channel().close();
                } catch (IOException cex) {
                // ignore on close
                }
            }
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Selector(java.nio.channels.Selector)

Example 39 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project chuidiang-ejemplos by chuidiang.

the class Client method main.

public static void main(String[] args) {
    try (ServerSocketChannel server = ServerSocketChannel.open()) {
        server.bind(new InetSocketAddress("0.0.0.0", 5557));
        while (true) {
            SocketChannel client = server.accept();
            new Thread(new Client(client)).start();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 40 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project chuidiang-ejemplos by chuidiang.

the class Client method main.

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();
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Aggregations

ServerSocketChannel (java.nio.channels.ServerSocketChannel)274 SocketChannel (java.nio.channels.SocketChannel)156 InetSocketAddress (java.net.InetSocketAddress)128 IOException (java.io.IOException)96 ByteBuffer (java.nio.ByteBuffer)53 SelectionKey (java.nio.channels.SelectionKey)41 ServerSocket (java.net.ServerSocket)37 Test (org.junit.Test)27 Socket (java.net.Socket)24 ClosedChannelException (java.nio.channels.ClosedChannelException)22 Selector (java.nio.channels.Selector)22 ClosedSelectorException (java.nio.channels.ClosedSelectorException)15 InetAddress (java.net.InetAddress)14 CancelledKeyException (java.nio.channels.CancelledKeyException)11 EOFException (java.io.EOFException)8 SocketException (java.net.SocketException)8 BindException (java.net.BindException)7 SocketAddress (java.net.SocketAddress)7 Test (org.junit.jupiter.api.Test)7 OutgoingPacket (com.twitter.heron.common.network.OutgoingPacket)6