NIO – ServerSocketChannel代码示例

package player.kent.chen.temp.learnnio.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class PlayServerSocketChannel {

    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(17547));
        ssc.configureBlocking(false);

        System.out.println("开始侦听连接...");
        while (true) {
            SocketChannel sc = ssc.accept();

            if (sc == null) {//非阻塞模式下,如果没有连接,accept()方法不会阻塞,而是直接返回null
                Thread.sleep(2000);
            } else {
                System.out.println("进来了一个连接。来自:" + sc.socket().getRemoteSocketAddress());
                sc.write(ByteBuffer.wrap("尊姓大名: \n".getBytes())); //向客户端要求输入

                //读入客户端的输入
                ByteBuffer inputBuffer = ByteBuffer.allocate(10);
                sc.read(inputBuffer);
                inputBuffer.flip();
                String clientName = new String(inputBuffer.array());

                sc.write(ByteBuffer.wrap(("幸会," + clientName).getBytes())); //问候客户端
                sc.write(ByteBuffer.wrap(("\n再见").getBytes()));

                sc.close(); //断开连接
            }

        }

    }
}

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.