[問題] c socket select nonblocking問題
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
mac os 10.8.3 使用c gcc
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
無
問題(Question):
要寫一個小型的msn 不過遇到server寫資料給client client時
預期可以馬上顯示 但必須多按一個enter才收得到
預期的正確結果(Expected Output):
客戶端一登入立刻收到一個 >的符號(類似向command的意思)
至於從客戶收過來的訊息就完全沒有問題
錯誤結果(Wrong Output):
當我的客戶端一登入 沒有立即顯示出> 而是必須按下enter時才會跳出
從server端寫來的>符號
程式碼(Code):(請善用置底文網頁, 記得排版)
說明一下我的程式碼
FD_ZERO(&allset);
FD_ZERO(&wsetsave);
FD_SET(listenfd, &allset);
for ( ; ; ) {
rset = allset; /* structure assignment */
wset=wsetsave;;
nready = select(maxfd+1, &rset, &wset, NULL, NULL);
if (FD_ISSET(listenfd, &rset)) { /* new client connection */
中間略
}
=========上面是select的初始化=============
=================開始處理資料=====================
for (i = 0; i <= maxi; i++) { /* check all clients for data */
if ( (sockfd = client[i]) < 0)
continue;
if (FD_ISSET(sockfd, &rset)) {
if ( (n = read(sockfd, buf, MAXLINE)) == 0) {
/*connection closed by client */
close(sockfd);
FD_CLR(sockfd, &allset);
client[i] = -1;
} else
{
if(省略
{
write(sockfd, buf, n);
}
}
if (--nready <= 0)
break; /* no more readable descriptors */
}
else if(FD_ISSET(sockfd, &wset)) (想法:第一次當這個socket建好後就可
{ 寫)
if((j=write(sockfd,">",1))==0) <=這個地方寫出去後client
printf("write error"); 按一次enter才收得到
FD_CLR(sockfd,&wsetsave);
}
}
完整程式碼server http://pastecode.org/index.php/view/2622691d
client http://pastecode.org/index.php/view/82395749
補充說明(Supplement):
另外我在建立連線完後立刻也嘗試了一次寫給client >這個符號
也是無法馬上收到他會跟我上面這個符號按完enter就出現>>這樣
變成一起出現 ,是buffer設計的問題嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 1.175.131.169
※ 編輯: tt801002 來自: 1.175.131.169 (04/18 15:03)
※ 編輯: tt801002 來自: 1.175.131.169 (04/18 15:07)
※ 編輯: tt801002 來自: 1.175.131.169 (04/18 15:08)
※ 編輯: tt801002 來自: 1.175.131.169 (04/18 15:11)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章