python第10天(下)

 

一:IO模型介绍

IO发生时涉及的对象和步骤

  对于一个网络IO(network IO),它会涉及到两个系统对象,一个是调用这个IO的process (or thread),另一个就是系统内核(kernel)

  当一个read操作发生时,该操作会经历两个阶段:

   1)等待数据准备 (Waiting for the data to be ready)

  2)将数据从内核拷贝到进程中(Copying the data from the kernel to the process) 

  记住这两点很重要,因为这些IO模型的区别就是在两个阶段上各有不同的情况

 

 1  1 import socket
 2  2 server=socket.socket()
 3  3 server.bind(("localhost",6969))
 4  4 server.listen()
 5  5 print("等待用户链接")
 6  6 while True:
 7  7     conn,addr=server.accept()
 8  8     while True:
 9  9         conn.send(("%s have connected to server"%addr).encode())
10 10         data=conn.recv(1024)
11 11         print("from client",data.decode())
12 12 
13 13 
14 14 import socket
15 15 client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
16 16 client.connect(("localhost",6969))
17 17 while True:
18 18     data=client.recv(1024)
19 19     print("from server:",data.decode())
20 20     client.send("hellow".encode())
阻塞IO

 1 import socket,time
 2 server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 3 server.bind(("localhost",6969))
 4 server.listen()
 5 server.setblocking(False)#设置为非阻塞,默认为阻塞
 6 print("等待用户链接")
 7 while True:
 8     try:
 9         conn,addr=server.accept()
10         conn.send("you have connected to server".encode())
11         data=conn.recv(1024)
12         print("from client",data.decode())
13         conn.close()
14     except Exception as e:
15         print(e)
16         time.sleep(4)
17 ##########
18 import socket,time
19 client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
20 while True:
21     client.connect(("localhost", 6969))
22     data=client.recv(1024)
23     print("from server:",data.decode())
24     client.send("hellow".encode())
25     time.sleep(2)
26     break
非阻塞IO

由于设置了非阻塞IO(setblocking())所以在accept()的时候会报错,因为抓住了错误,所以开始会输出错误信息 ,有个问题就是服务端接收不到了客户端的数据

  

猜你喜欢

转载自www.cnblogs.com/Mr-l/p/10426163.html
今日推荐