前幾篇文章介紹了nio的幾個主要構件,包括緩衝區buffer、傳輸通道channel、訊息選擇器selector以及訊息類別selectionkey,接下來我們通過乙個聊天室的例子來了解一下以上各種元件的用法。聊天室分為伺服器端和客戶端,伺服器端接收客戶端發來的請求訊息,並生成乙個channel來處理客戶端的訊息;客戶端生成channel來連線伺服器,傳送訊息,然後再註冊乙個新的channel來接收伺服器端發來的訊息。
伺服器
selector selector = selector.open();
serversocketchannel channel;
channel = serversocketchannel.open();
channel.bind(new inetsocketaddress("127.0.0.1", 9999));
channel.configureblocking(false);
channel.register(selector, selectionkey.op_accept);
system.out
.println("server is running!");
while (true)
}
2.處理客戶端發來的訊息
/**
* 處理連線訊息
*@param selector
*@param key
*@throws ioexception
*@throws exception
*/public
void
dealconnection(selector selector, selectionkey key)
throws ioexception, exception
if (key.isconnectable()) else
if (key.isreadable()) else
if (key.iswritable())
}
3.生成新的channel處理客戶端發來的訊息
/**
* 伺服器端註冊channel
*@param selector
*@param key
*@throws ioexception
*@throws closedchannelexception
*/public
void
registerchannel(selector selector, selectionkey key)
throws ioexception, closedchannelexception
sc.configureblocking(false);
sc.register(selector, selectionkey.op_read);
key.interestops(selectionkey.op_accept);
system.out.println("server is listening from client :" + sc.getremoteaddress());
sc.write(charset.encode("請輸入姓名"));
}
4.將客戶端訊息廣播到其他客戶端
/**
* 廣播訊息
*@param selector
*@param srcchannel
*@param content
*@throws ioexception
*/public
void
broadcast(selector selector, socketchannel srcchannel, string content) throws ioexception
}}
到此伺服器端的功能基本完成
客戶端1.註冊channel連線服務端
sc = socketchannel.open();
selector = selector.open();
sc.connect(new inetsocketaddress("127.0.0.1", 9999));
sc.configureblocking(false);
sc.register(selector, selectionkey.op_write | selectionkey.op_read);
2.建立乙個channel來接收服務端發來的訊息
new thread(new runnable() }}
catch (ioexception io){}}
}).start();
3.處理伺服器發來的訊息
/**
* 處理伺服器發來的訊息
*@param sk
*@throws ioexception
*/private
void
dealmsg(selectionkey sk) throws ioexception
}
NIO實現網路聊天室
public class tcpnioclient 5.準備乙個資料存入到緩衝區 bytebuffer buffer bytebuffer.wrap 你好,伺服器 getbytes 6.通過socketchannel 符合tcp協議socket要求channel物件傳送 socket.write b...
mysql 聊天室 聊天室php mysql 六
聊天室php mysql 六 相應的 資料庫 phpmyadmin mysql dump 主機 localhost 3306 資料庫 study28 資料表的結構 chat user create table chat user userid varchar 20 not null,passwd v...
聊天室程式
伺服器 include include include include include include include include define servport 8081 伺服器端口號 define bufsize 200 最大傳輸量 int main int args,char argv s...