esp 32 上測(cè)試
_thread 最多創(chuàng)建8個(gè)線程 所以要限制客戶端數(shù)量
接收中文的時(shí)候遇到一個(gè)坑
客戶端用SocketTool.exe創(chuàng)建的 發(fā)生過(guò)來(lái)的文本編碼好像不是標(biāo)準(zhǔn)的utf-8導(dǎo)致亂碼
接收中文淘菩,請(qǐng)保證客戶端發(fā)送過(guò)來(lái)的內(nèi)容為utf-8
import _thread
import socket
# 檢測(cè)端口是否使用
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服務(wù)端
class SocketServer(object):
def __init__(self, ip, port, parse_def) -> None:
"""
* ip 服務(wù)ip
* port 服務(wù)端口
* parse_def 解析接受到的數(shù)據(jù)函數(shù)
* client_max 最大客戶端數(shù)量
* client_list 客戶端列表
* is_run 是否正在運(yùn)行
* server_socket 服務(wù)端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
# 啟動(dòng)服務(wù)
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!')
# 停止服務(wù)
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')