服务端处理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