利用NIO構造簡單的聊天功能

2021-06-27 12:35:56 字數 2139 閱讀 2206

public class socketselector 

public void init(string... args) throws ioexception

selector selector = selector.open();

serversocketchannel serversocketchannel = serversocketchannel.open();

serversocketchannel.configureblocking(false);

serversocketchannel.socket().bind(new inetsocketaddress(port));

system.out.println("1111");

serversocketchannel.register(selector, selectionkey.op_accept);

system.out.println("wille to cycle..");

while(true)

system.out.println(n);

iterator it = selector.selectedkeys().iterator();

while(it.hasnext())

if(selectionkey.isreadable())}}

}private bytebuffer buf = bytebuffer.allocate(1024);

protected void readdatafromchannel(selectionkey selectionkey) throws ioexception

buf.clear();

}if (count < 0)

}private void sayhello(socketchannel socketchannel) throws ioexception

private void registerchannel(selector selector,

socketchannel socketchannel, int opread) throws ioexception

socketchannel.configureblocking(false);

socketchannel.register(selector, opread);

system.out.println("註冊成功——讀"); }

}

public class clientsocketselector 

public void init(string...args) throws ioexception

socketchannel socketchannel = socketchannel.open();

socketchannel.configureblocking(false);

socketchannel.connect(new inetsocketaddress("localhost", port));//不能用socketchannel.socket().connect();親身實踐證明!用了就不能正常通訊

socketchannel.register(selector, selectionkey.op_connect);

while(true)

iterator it = selector.selectedkeys().iterator();

while(it.hasnext())

if (key.isreadable()) }}

}private bytebuffer buf = bytebuffer.allocate(1024);

protected void readdatafromchannel(selectionkey key) throws unsupportedencodingexception, ioexception

int count = 0;

while((count = sc.read(buf)) > 0)

}}

原本以為只要一直讓通道處於就緒狀態就能不斷的接收資料(isreadable),測試後發現,一直處於被選擇的鍵中,不能夠接收到最新的資料。

只有將該鍵從已選擇的鍵中取消,才能重新獲得資料。

php聊天功能 php實現簡單聊天功能

php實現簡單聊天功能 1 建立聊天訊息表,其表的字段有訊息內容,傳送時間和傳送者的名稱 sql create table guanhui message id int 10 not null auto increment comment 訊息id content varchar 255 not n...

使用NIO實現乙個群組聊天功能

nio no blocking io或者new io 非阻塞io,是相對於傳統io來說,其意義在於網路io的非阻塞性。其工作流程 buffer 資料的載體 channel 客戶端到服務端的通道,負責資料 buffer 的傳輸 selector 多路復用器,用於監聽channel的事件 可對應多個ch...

python socket 簡單實現聊天功能

今天看了下python的socket,想實現下兩台電腦的聊天功能 覺得這樣好像自己寫出個簡易版qq沒問題了 於是動手開始實現。首先是伺服器端 from socket import from time import ctime host port 80 埠號,伺服器與客戶端要一致 bufsiz 102...