socket基础实例(一个服务端对应一个客户端情形)

服务端处理1个客户端的例子

 

运行结果:

(1) while(accept+if(recv)) 情形

执行服务端进程:

[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条指令无响应


[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条指令也无响应

[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)

   这种情形是不正常的,必须避免这种写法。

(3) 第3种情形:while(accept + while(recv))

也是现在我们想要的情形:server与1个client进行交互操作,当第1个client退出时,server会执行while循环体的起始代码,即继续等待下一个client,而不是像第(2)种情形一样,在一个可能不存在的套接字上recv/send数据。

执行服务端:

[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

posted @ 2014-09-21 18:57  咚咚锵锵  阅读(899)  评论(0编辑  收藏  举报