java nio 聊天室_Java NIO 聊天室实例

最近写了个Java NIO聊天室聊天的程序,NIO学习起来比较困难的,我的代码能给大家起到一个抛砖引玉的作用!

服务端:packagetest.javanio;

/**

* @author

* @version

* CreateTime:2010-12-1 下午05:12:11

* Description:

*/

importjava.io.IOException;

importjava.net.InetSocketAddress;

importjava.nio.ByteBuffer;

importjava.nio.channels.SelectionKey;

importjava.nio.channels.Selector;

importjava.nio.channels.ServerSocketChannel;

importjava.nio.channels.SocketChannel;

importjava.util.Date;

importjava.util.Iterator;

importjava.util.logging.Level;

importjava.util.logging.Logger;

publicclassMySocketServerimplementsRunnable {

privatebooleanrunning;

privateSelector selector;

String writeMsg;

StringBuffer sb =newStringBuffer();

SelectionKey ssckey;

publicMySocketServer() {

running =true;

}

publicvoidinit() {

try{

selector = Selector.open();

ServerSocketChannel ssc = ServerSocketChannel.open();

ssc.configureBlocking(false);

ssc.socket().bind(newInetSocketAddress(2345));

ssckey = ssc.register(selector, SelectionKey.OP_ACCEPT);

System.out.println("server is starting..."+newDate());

}catch(IOException ex) {

Logger.getLogger(MySocketServer.class.getName()).log(Level.SEVERE,

null, ex);

}

}

publicstaticvoidmain(String[] args) {

MySocketServer server =newMySocketServer();

newThread(server).start();

}

publicvoidexecute() {

try{

while(running) {

intnum = selector.select();

if(num >0) {

Iterator it = selector.selectedKeys()

.iterator();

while(it.hasNext()) {

SelectionKey key = it.next();

it.remove();

if(!key.isValid())

continue;

if(key.isAcceptable()) {

System.out.println("isAcceptable");

getConn(key);

}elseif(key.isReadable()) {

System.out.println("isReadable");

readMsg(key);

}

elseif(key.isValid() && key.isWritable()) {

if(writeMsg !=null) {

System.out.println("isWritable");

writeMsg(key);

}

}

else

break;

}

}

Thread.yield();

}

}catch(IOException ex) {

Logger.getLogger(MySocketServer.class.getName()).log(Level.SEVERE,

null, ex);

}

}

privatevoidgetConn(SelectionKey key)throwsIOException {

ServerSocketChannel ssc = (ServerSocketChannel) key.channel();

SocketChannel sc = ssc.accept();

sc.configureBlocking(false);

sc.register(selector, SelectionKey.OP_READ);

System.out.println("build connection :"

+ sc.socket().getRemoteSocketAddress());

}

privatevoidreadMsg(SelectionKey key)throwsIOException {

sb.delete(0, sb.length());

SocketChannel sc = (SocketChannel) key.channel();

System.out.print(sc.socket().getRemoteSocketAddress() +" ");

ByteBuffer buffer = ByteBuffer.allocate(1024);

buffer.clear();

intlen =0;

StringBuffer sb =newStringBuffer();

while((len = sc.read(buffer)) >0) {

buffer.flip();

sb.append(newString(buffer.array(),0, len));

}

if(sb.length() >0)

System.out.println("get from client:"+ sb.toString());

if(sb.toString().trim().toLowerCase().equals("quit")) {

sc.write(ByteBuffer.wrap("BYE".getBytes()));

System.out.println("client is closed "

+ sc.socket().getRemoteSocketAddress());

key.cancel();

sc.close();

sc.socket().close();

}else{

String toMsg = sc.socket().getRemoteSocketAddress() +"said:"

+ sb.toString();

System.out.println(toMsg);

writeMsg = toMsg;

/*

* Iterator it=key.selector().keys().iterator();

*

* while(it.hasNext()){ SelectionKey skey=it.next();

* if(skey!=key&&skey!=ssckey){ SocketChannel client=(SocketChannel)

* skey.channel(); client.write(ByteBuffer.wrap(toMsg.getBytes()));

* }

*

* }

*/

/*

*

* key.attach(toMsg);

* key.interestOps(key.interestOps()|SelectionKey.OP_WRITE);

*/

Iterator it = key.selector().keys().iterator();

while(it.hasNext()) {

SelectionKey skey = it.next();

if(skey != key && skey != ssckey) {

if(skey.attachment() !=null) {

String str = (String) skey.attachment();

skey.attach(str + toMsg);

}else{

skey.attach(toMsg);

}

skey

.interestOps(skey.interestOps()

| SelectionKey.OP_WRITE);

}

}

selector.wakeup();// 可有可无

}

}

publicvoidrun() {

init();

execute();

}

privatevoidwriteMsg(SelectionKey key)throwsIOException {

System.out.println("++++enter write+++");

SocketChannel sc = (SocketChannel) key.channel();

String str = (String) key.attachment();

sc.write(ByteBuffer.wrap(str.getBytes()));

key.interestOps(SelectionKey.OP_READ);

}

}

客户端:packagetest.javanio;

/**

* @author

* @version

* CreateTime:2010-12-1 下午05:12:46

* Description:

*/

importjava.io.BufferedReader;

importjava.io.IOException;

importjava.io.InputStreamReader;

importjava.net.InetSocketAddress;

importjava.nio.ByteBuffer;

importjava.nio.channels.Selector;

importjava.nio.channels.SocketChannel;

importjava.util.logging.Level;

importjava.util.logging.Logger;

importjava.util.Currency.*;

publicclassMySocketClientimplementsRunnable {

Selector selector;

booleanrunning;

SocketChannel sc;

publicMySocketClient() {

running =true;

}

publicvoidinit() {

try{

sc = SocketChannel.open();

sc.configureBlocking(false);

sc.connect(newInetSocketAddress("localhost",2345));

}catch(IOException ex) {

Logger.getLogger(MySocketClient.class.getName()).log(Level.SEVERE,

null, ex);

}

}

publicstaticvoidmain(String[] args) {

MySocketClient client =newMySocketClient();

newThread(client).start();

}

publicvoidexecute() {

intnum =0;

try{

while(!sc.finishConnect()) {

}

}catch(IOException ex) {

Logger.getLogger(MySocketClient.class.getName()).log(Level.SEVERE,

null, ex);

}

ReadKeyBoard rkb =newReadKeyBoard();

newThread(rkb).start();

while(running) {

try{

ByteBuffer buffer = ByteBuffer.allocate(1024);

buffer.clear();

StringBuffer sb =newStringBuffer();

Thread.sleep(500);

while((num = sc.read(buffer)) >0) {

sb.append(newString(buffer.array(),0, num));

buffer.clear();

}

if(sb.length() >0)

System.out.println(sb.toString());

if(sb.toString().toLowerCase().trim().equals("bye")) {

System.out.println("closed....");

sc.close();

sc.socket().close();

rkb.close();

running =false;

}

}catch(InterruptedException ex) {

Logger.getLogger(MySocketClient.class.getName()).log(

Level.SEVERE,null, ex);

}catch(IOException ex) {

Logger.getLogger(MySocketClient.class.getName()).log(

Level.SEVERE,null, ex);

}

}

}

publicvoidrun() {

init();

execute();

}

classReadKeyBoardimplementsRunnable {

booleanrunning2 =true;

publicReadKeyBoard() {

}

publicvoidclose() {

running2 =false;

}

publicvoidrun() {

BufferedReader reader =newBufferedReader(newInputStreamReader(

System.in));

while(running2) {

try{

System.out.println("enter some commands:");

String str = reader.readLine();

sc.write(ByteBuffer.wrap(str.getBytes()));

}catch(IOException ex) {

Logger.getLogger(ReadKeyBoard.class.getName()).log(

Level.SEVERE,null, ex);

}

}

}

}

}

原文链接:http://gcguchao8888-sina-com.iteye.com/blog/839021

【编辑推荐】多线程NIO客户端实例

用nio实现Echo服务

Java NIO 深入研究

Java NIO聊天窗口实例

Java NIO 经典实例代码

推荐阅读

package night; import java.net .InetSocketAddress; import java.io .IOException; import java.io .BufferedReader; import java.io .InputStreamReader; import java.nio.ByteBuffer; import java.n>>>详细阅读

地址:http://www.17bianji.com/kaifa2/Java/1329.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值