java-nio-client聊天室客户端

2022-3-13 diaba IO

package com.jiucaiyuan.net.nio;

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

/**
 * @Author jiucaiyuan  2022/3/13 11:04
 * @mail services@jiucaiyuan.net
 */

public class Client {
    public static void main(String[] args) throws IOException {
        //1 获取通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9999));
        //2 切换成非阻塞模式
        socketChannel.configureBlocking(false);
        //3 分配指定大小的缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //4 接收输入数据发送给服务端
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.println("请输入:");
            String msg = scanner.nextLine();
            byteBuffer.put(("波仔:"+msg).getBytes());
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            byteBuffer.clear();
        }
    }
}

发表评论:

Powered by emlog 京ICP备15045175号-1 Copyright © 2022