socket nio 多线程接收客户端信息

在连接数很大的情况下,使用Selector能减少并发线程数,减少上下文切换的消耗,非阻塞IO使得具备流程的读写。


package main;
 
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class Server {
    private final int PORT = 1234;
    private ExecutorService pool;
    private ServerSocketChannel ssc;
    private Selector selector;
    private static Charset charset = Charset.forName("utf-8");
    private int n;
     
    public static void main(String[] args) throws IOException{
        Server server = new Server();
        server.doService();
    }
     
    public Server() throws IOException{
        pool = Executors.newFixedThreadPool(5);
         
        ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ServerSocket ss = ssc.socket();
        ss.bind(new InetSocketAddress(PORT));
        selector = Selector.open();
        ssc.register(selector,SelectionKey.OP_ACCEPT);
        System.out.println("Server started...");
    }
     
    public void doService(){
        while(true){
            try{
                n = selector.select();
            }catch (IOException e) {
                throw new RuntimeException("Selector.select()异常!");
            }
            if(n==0)
                continue;
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iter = keys.iterator();
            while(iter.hasNext()){
                SelectionKey key = iter.next();
                iter.remove();
                if(key.isAcceptable()){
                    SocketChannel sc = null;
                    try{
                        sc = ((ServerSocketChannel)key.channel()).accept();
                        sc.configureBlocking(false);
                        System.out.println("客户端:"+sc.socket().getInetAddress().getHostAddress()+" 已连接");
                        SelectionKey k = sc.register(selector, SelectionKey.OP_READ);
                        ByteBuffer buf = ByteBuffer.allocate(1024);
                        k.attach(buf);
                    }catch (Exception e) {
                        try{
                            sc.close();
                        }catch (Exception ex) {
                        }
                    }
                }
                else if(key.isReadable()){
                    key.interestOps(key.interestOps()&(~SelectionKey.OP_READ));
                    pool.execute(new Worker(key));
                }
            }
        }
    }
     
    public static class Worker implements Runnable{
        private SelectionKey key;
        public Worker(SelectionKey key){
            this.key = key;
        }
         
        @Override
        public void run() {
            SocketChannel sc = (SocketChannel)key.channel();
            ByteBuffer buf = (ByteBuffer)key.attachment();
            buf.clear();
            int len = 0;
            try{
                while((len=sc.read(buf))>0){//非阻塞,立刻读取缓冲区可用字节
                    buf.flip();
                    System.out.println("客户端:"+charset.decode(buf).toString());
                    buf.clear();
                }
                if(len==-1){
                    System.out.println("客户端断开。。。");
                    sc.close();
                }
                //没有可用字节,继续监听OP_READ
                key.interestOps(key.interestOps()|SelectionKey.OP_READ);
                key.selector().wakeup();
            }catch (Exception e) {
                try {
                    sc.close();
                } catch (IOException e1) {
                }
            }
        }
    }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 NIO(Non-blocking I/O)实现 Java 的客户端和服务端可以提高网络通信的效率。下面是一个简单的示例,演示了如何使用 NIO 实现一个简单的客户端和服务端。 首先是服务端代码: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class NioServer { private static int BUF_SIZE = 1024; private static int PORT = 8080; private static int TIMEOUT = 3000; public static void main(String[] args) { selector(); } public static void handleAccept(SelectionKey key) throws IOException { ServerSocketChannel ssChannel = (ServerSocketChannel) key.channel(); SocketChannel sc = ssChannel.accept(); sc.configureBlocking(false); sc.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocateDirect(BUF_SIZE)); } public static void handleRead(SelectionKey key) throws IOException { SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer buf = (ByteBuffer) key.attachment(); int bytesRead = sc.read(buf); while (bytesRead > 0) { buf.flip(); while (buf.hasRemaining()) { System.out.print((char) buf.get()); } System.out.println(); buf.clear(); bytesRead = sc.read(buf); } if (bytesRead == -1) { sc.close(); } } public static void handleWrite(SelectionKey key) throws IOException { ByteBuffer buf = (ByteBuffer) key.attachment(); buf.flip(); SocketChannel sc = (SocketChannel) key.channel(); while (buf.hasRemaining()) { sc.write(buf); } buf.compact(); } public static void selector() { Selector selector = null; ServerSocketChannel ssc = null; try { selector = Selector.open(); ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(PORT)); ssc.configureBlocking(false); ssc.register(selector, SelectionKey.OP_ACCEPT); while (true) { if (selector.select(TIMEOUT) == 0) { System.out.println("=="); continue; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if (key.isAcceptable()) { handleAccept(key); } if (key.isReadable()) { handleRead(key); } if (key.isWritable() && key.isValid()) { handleWrite(key); } if (key.isConnectable()) { System.out.println("isConnectable = true"); } iterator.remove(); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (selector != null) { selector.close(); } if (ssc != null) { ssc.close(); } } catch (IOException e) { e.printStackTrace(); } } } } ``` 然后是客户端代码: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Scanner; import java.util.Set; public class NioClient { private static int BUF_SIZE = 1024; private static int PORT = 8080; private static int TIMEOUT = 3000; public static void main(String[] args) throws IOException { SocketChannel clientChannel = SocketChannel.open(); clientChannel.configureBlocking(false); Selector selector = Selector.open(); clientChannel.register(selector, SelectionKey.OP_CONNECT); clientChannel.connect(new InetSocketAddress(PORT)); while (true) { if (selector.select(TIMEOUT) == 0) { System.out.println("=="); continue; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if (key.isConnectable()) { SocketChannel channel = (SocketChannel) key.channel(); if (channel.isConnectionPending()) { channel.finishConnect(); } channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); Scanner scanner = new Scanner(System.in); String message = scanner.nextLine(); channel.write(ByteBuffer.wrap(message.getBytes())); } else if (key.isReadable()) { SocketChannel channel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(BUF_SIZE); int bytesRead = channel.read(buffer); while (bytesRead > 0) { buffer.flip(); while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } System.out.println(); buffer.clear(); bytesRead = channel.read(buffer); } } iterator.remove(); } } } } ``` 这里的服务端监听端口为 8080,客户端连接的端口也为 8080。客户端首先向服务端发送一条消息,然后等待服务端的响应。当服务端接收客户端的消息后,就会输出到控制台,并将消息原封不动地返回客户端客户端接收到服务端的响应后,也会将其输出到控制台。 注意,这个示例只是一个简单的演示,实际开发中需要考虑更多的因素,例如线程安全、异常处理等等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值