首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 互联网 >

Java NIO 非拥塞式 C/S结构简易 多人聊天室

2013-10-27 
Java NIO 非阻塞式 C/S结构简易 多人聊天室使用JAVA 的 NIO 实现了服务器端 / 客户端 结构的简易多人聊天

Java NIO 非阻塞式 C/S结构简易 多人聊天室

使用JAVA 的 NIO 实现了服务器端 / 客户端 结构的简易多人聊天室:

说明都在代码注释里了,希望可以不断完善

服务器端:

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.nio.charset.Charset;import java.util.Scanner;public class NClient {private Selector selector = null;static final int port = 3330;private Charset charset = Charset.forName("UTF-8");private SocketChannel sc = null;public void init() throws IOException{selector = Selector.open();//连接远程主机的IP和端口sc = SocketChannel.open(new InetSocketAddress("127.0.0.1",port));sc.configureBlocking(false);sc.register(selector, SelectionKey.OP_READ);//开辟一个新线程来读取从服务器端的数据new Thread(new ClientThread()).start();//在主线程中 从键盘读取数据输入到服务器端Scanner scan = new Scanner(System.in);while(scan.hasNextLine()){String line = scan.nextLine();sc.write(charset.encode(line));}}private class ClientThread implements Runnable{public void run(){try{while(selector.select() > 0){for(SelectionKey sk : selector.selectedKeys()){selector.selectedKeys().remove(sk);if(sk.isReadable()){//使用 NIO 读取 Channel中的数据SocketChannel sc = (SocketChannel)sk.channel();ByteBuffer buff = ByteBuffer.allocate(1024);String content = "";while(sc.read(buff) > 0){buff.flip();content += charset.decode(buff);}System.out.println("聊天信息: " + content);sk.interestOps(SelectionKey.OP_READ);}}}}catch (IOException io){}}}public static void main(String[] args) throws IOException{new NClient().init();}}

可以输入中文字符,采用UTF-8来进行编码。

热点排行