esp 32 上测试
_thread 最多创建8个线程 所以要限制客户端数量
接收中文的时候遇到一个坑
客户端用SocketTool.exe创建的 发生过来的文本编码好像不是标准的utf-8导致乱码
接收中文,请保证客户端发送过来的内容为utf-8
import _thread
import socket
# 检测端口是否使用
def check_port_in_use(port, host='127.0.0.1') -> bool:
s = None
try:
s = socket.socket()
s.settimeout(1)
s.connect((host, int(port)))
print(port, ' has been used')
return True
except OSError:
print(port, ' don\'t use')
return False
finally:
if s:
s.close()
# Socket服务端
class SocketServer(object):
def __init__(self, ip, port, parse_def) -> None:
"""
* ip 服务ip
* port 服务端口
* parse_def 解析接受到的数据函数
* client_max 最大客户端数量
* client_list 客户端列表
* is_run 是否正在运行
* server_socket 服务端socket
"""
self.ip = ip
self.port = port
self.parse_def = parse_def
self.client_max = 3
self.client_list = []
self.is_run = False
self.server_socket = None
pass
# 启动服务
def start(self):
if not self.is_run:
_thread.start_new_thread(self.do_create_server, (socket.socket(),))
print(self, 'start server win!')
else:
print(self, 'start server lose!')
# 停止服务
def stop(self):
print(self, 'stop server ... start!')
if self.client_list:
for item in self.client_list:
print(item)
try:
item[0].close()
print(item[1], 'client close win!')
except OSError:
print(item[1], 'client close lose!')
else:
print('client list is null')
if self.server_socket:
try:
self.server_socket.close()
print(self.server_socket, 'server close win!')
except OSError:
print(self.server_socket, 'server close lose!')
self.is_run = False
print(self, 'stop server ... end!')
def do_create_server(self, s):
self.is_run = True
if not check_port_in_use(self.port):
print('server ip:', self.ip, ' port:', self.port)
self.server_socket = s
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind((self.ip, self.port))
self.server_socket.listen(0)
self.server_socket.settimeout(1.0)
while self.is_run:
try:
conn, address = self.server_socket.accept()
except OSError:
continue
if len(self.client_list) < self.client_max:
_thread.start_new_thread(self.do_client_read, (conn, address))
print('client list add ', address)
else:
print('client size > ', self.client_max)
try:
conn.close()
except OSError:
pass
self.is_run = False
def do_client_read(self, conn, address):
self.client_list.append((conn, address))
print('start read ', address)
while self.is_run:
try:
data = conn.recv(4096)
if len(data) == 0:
break
data = str(data, 'utf-8')
print(address, 'read data str = ', data)
self.parse_def(data)
except BaseException:
pass
self.client_list.remove((conn, address))
print('client close from:', address)
conn.close()
食用方法
print('start server')
sss = SocketServer('192.168.50.17',60000,do_parse_data)
sss.start()
time.sleep(20)
sss.stop()
time.sleep(10)
sss.start()
print('end server')
网友评论