首页>代码>java NIO简单聊天对话实例demo分享>/NIO-Chat-Client/src/com/zuidaima/client/ClientService.java
package com.zuidaima.client;


import com.zuidaima.client.utils.CharactorUtils;
import com.zuidaima.client.utils.ChatClientConfig;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;


/**
 * 
 * 客户端启动入口
 *
 */
public class ClientService {
    
    public static SocketChannel clientChannel = null;// TCP网络通道
    public static Selector selector = null;          // 选择器 
    
    public static void main(String[] args) throws IOException {
        
    	// 打开 SocketChannel
        clientChannel = SocketChannel.open(new InetSocketAddress(ChatClientConfig.HOSTS, ChatClientConfig.PORT));
        
        // 通道设置为非阻塞模式
        clientChannel.configureBlocking(false);
        
        // 打开选择器
        selector = Selector.open();
        
        // 通道注册到 选择器上 
        clientChannel.register(selector, SelectionKey.OP_READ);
        
        // 启动线程
        ReadThread readThread = new ReadThread();
        readThread.start();
        
        // 发送消息
        sendMsg();
    }
    
    /**
     *  
     *  发送消息的具体实现
     *  
     */
    public static void sendMsg() {
    	 
    	// 创建一个容量为1024字节的ByteBuffe
        ByteBuffer buffer = ByteBuffer.allocate(ChatClientConfig.BUFFER_SIZE);
        
        // 接受控制台输入的消息
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        String msg = null;
        System.out.print("请输入用户名:");
        buffer.clear();
        try {
            while ((msg = br.readLine()) != null) {
    
                buffer.put(CharactorUtils.utf16Encode(msg));
                buffer.flip(); 
                
                clientChannel.write(buffer);
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
}
最近下载更多
xushijie  LV11 2020年12月23日
admin_zyg  LV2 2020年8月3日
2187693636  LV12 2020年4月6日
guoruchao  LV13 2019年11月5日
kimshell  LV3 2019年10月14日
jaden12  LV3 2019年10月10日
whywhywhy  LV10 2019年9月20日
zxc164042899  LV4 2019年4月26日
912299793  LV21 2019年4月18日
最代码酒酒  LV20 2019年4月16日
最近浏览更多
851690469  LV1 2023年10月18日
2017143155  LV12 2023年6月24日
人工智能4708  LV11 2023年5月8日
hy0047  LV4 2023年4月18日
微信网友_5981140928106496  LV5 2023年3月22日
魏振华  LV1 2023年3月12日
yohohero  LV1 2023年1月14日
qwdqwdqw  LV3 2022年12月2日
brucega  LV3 2022年6月3日
ganglianhuo  LV9 2022年4月8日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友