一个用java的NIO实现的socket的客户端和服务端的demo

这个demo没有使用selector,无法使用一个单线程很好的处理多个channel的消息,性能没有使用selector高

服务端

public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverS = ServerSocketChannel.open();
        serverS.bind(new InetSocketAddress(8080));
        ByteBuffer inB = ByteBuffer.allocate(1024);
        ByteBuffer outB = ByteBuffer.allocate(1024);
        while(true){
            SocketChannel accept = serverS.accept();
            MsgHandler.sendMsg(outB, "你好,客户端,连接建立成功", accept);
            while(accept.read(inB) != -1){
                String msg = MsgHandler.receiveStrMsg(inB, accept);
                System.out.println(msg);
                MsgHandler.sendMsg(outB, "消息处理完毕,from服务器",accept);
            }
        }
    }
}

客户端

public class Client {
    public static void main(String[] args) throws Exception {
        SocketChannel clientC = SocketChannel.open();
        Scanner scanner = new Scanner(System.in);
        clientC.connect(new InetSocketAddress("localhost",8080));
        clientC.configureBlocking(false);
        ByteBuffer outB = ByteBuffer.allocate(1024);
        ByteBuffer inB = ByteBuffer.allocate(1024);
        while(true){
            while(clientC.read(inB) > 0){
                System.out.println(MsgHandler.receiveStrMsg(inB, clientC));
            }
            String msg = scanner.next();
            MsgHandler.sendMsg(outB, msg, clientC);
            if(msg.equals("exit")){
                clientC.close();
                return;
            }
        }
    }
}

消息处理类

public class MsgHandler {
    public static void sendMsg (ByteBuffer outB, String msg, SocketChannel channel){
        try {
            outB.put(msg.getBytes("UTF-8"));
            outB.flip();
            while(outB.hasRemaining()){
                channel.write(outB);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            outB.clear();
        }
    }
    public static String receiveStrMsg(ByteBuffer inB, SocketChannel channel){
        List<Byte> bList = new ArrayList<>();
        String msg = null;
        try {
            inB.flip();
            while(inB.hasRemaining()){
                bList.add(inB.get());
            }
            byte[] bytes = new byte[bList.size()];
            for(int i = 0;i < bList.size();i++){
                bytes[i] = bList.get(i);
            }
            msg = new String(bytes, "UTF-8");
        }
        catch (Exception e){
            e.printStackTrace();
        }finally {
            inB.clear();
            return msg;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值