本文实例讲述了Python实现socket非阻塞通讯功能。分享给大家供大家参考,具体如下:非阻塞
本文实例讲述了Python实现socket非阻塞通讯功能。分享给大家供大家参考,具体如下:
非阻塞需要多线程编程
服务端
方式1: 使用threading库实现多线程
基本方法和单进程基本写法一致, 将收发部分封装为函数以便开启其他线程:
import socket
import time
import threading
def handle_socket(conn, addr):
while True:
data = conn.recv(1024)
print(data.decode('utf-8'))
time.sleep(3)
send_data = 'got it'
conn.send(send_data.encode('utf-8'))
conn.close()
基本设置和调用部分: 绑定, 监听, 接受连接:
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0', 8888))
s.listen()
while True:
conn, addr = s.accept()
client_thread = threading.Thread(target=handle_socket, args=[conn, addr])
client_thread.start()
方式2: 通过继承StreamRequestHandler库实现多线程
收发部分写到handle方法中:
import socketserver
from socketserver import StreamRequestHandler
import time
class MyHandler(StreamRequestHandler):
def handle(self):
# addr = self.request.getpeername()
# print('get connection from ', addr)
# self.wfile.write('hello, thank for your connection'.encode())
while True:
datarecv = self.request.recv(1024)
if not datarecv:
break
time.sleep(3)
print(datarecv.decode())
self.request.send("got it".encode())
开启
myserver = socketserver.ThreadingTCPServer(('127.0.0.1', 8888), MyHandler)
myserver.serve_forever()
客户端
客户端:
import socket
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.connect(('127.0.0.1', 8888))
while True:
conn.send('hello'.encode())
data = conn.recv(1024)
print(data.decode())
Python
socket
非阻塞通讯