一個用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;
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章