服務端處理1個客戶端的例子socket
運行結果:oop
(1) while(accept+if(recv)) 情形spa
執行服務端進程:code
[root@localhost single_link]# ./server [server]: begin [server]: loop...... Client[127.0.0.1,49930]==>Server: 11 now send data to conn_id [server]: loop...... Client[127.0.0.1,49931]==>Server: 21 now send data to conn_id [server]: loop......
執行第1個客戶端進程,服務端對第2條指令無響應server
[root@localhost single_link]# ./client [client]: begin connect to dest host.. [Client]: loop......: input your word:>11 Server==>Client: 11 [Client]: loop......: input your word:>12
開戶第2個客戶端,並執行:服務端對第2條指令也無響應blog
[root@localhost single_link]# ./client [client]: begin connect to dest host.. [Client]: loop......: input your word:>21 Server==>Client: 21 [Client]: loop......: input your word:>22
(2)第2種情形:accept + while(recv)進程
這種情形是不正常的,必須避免這種寫法。input
(3) 第3種情形:while(accept + while(recv))class
也是如今咱們想要的情形:server與1個client進行交互操做,當第1個client退出時,server會執行while循環體的起始代碼,即繼續等待下一個client,而不是像第(2)種情形同樣,在一個可能不存在的套接字上recv/send數據。cli
執行服務端:
[root@localhost single_link]# ./server [server]: begin [server]: loop...... Client[127.0.0.1,49933]==>Server: 11 now send data to conn_id Client[127.0.0.1,49933]==>Server: 12 now send data to conn_id Client[127.0.0.1,49933]==>Server: 13 now send data to conn_id
執行第1個Client:
[root@localhost single_link]# ./client [client]: begin connect to dest host.. [Client]: loop......: input your word:>11 Server==>Client: 11 [Client]: loop......: input your word:>12 Server==>Client: 12 [Client]: loop......: input your word:>13 Server==>Client: 13 [Client]: loop......: input your word:>
在第1個client Ctrl+c退出後,若是第2個客戶端程序仍未關閉,服務端將會與第2個client進行交互操做:因而有了如下信息:
Client[127.0.0.1,49934]==>Server: 21
now send data to conn_id
[Client]: loop......: input your word:>
而後執行第2個client:
[root@localhost single_link]# ./client [client]: begin connect to dest host.. [Client]: loop......: input your word:>21
案例總結:
該實例驗證的是服務端:客戶端=1:1的情形,
從服務端程序邏輯上看,第1個while用於屬於accept/connect while循環,完成與client的鏈接操做,內部的while屬於recv/send循環操做,完成與client的數據傳輸操做。
若是第client1不關閉socket,服務端的recv/send while就不會退出,
因此當第client2鏈接到server的時候,connec和send都是成功的,但由於服務端正處於與client1的交互中而沒法響應send操做,因此client2會block在這裏,等待server的數據返回,
這時如題第1個client關閉了,server與client2