基于协程的,socket并发,server端永不断开
class TCPserver():
def server(self, server_ip, port):
s = socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind((server_ip, port))
s.listen(5)
print(f'TCP服务启动成功 IP:{IP},PORT:{PORT}')
self.socket = s
while True:
conn, addr = s.accept()
res = conn.recv(1024)
# 开启协程
gevent.spawn(self.talk, conn, addr)
self.genentlist.append(obj)
def talk(self, conn, addr):
with open('smartlabdemo/utils/tcpsocket.log', 'a') as f:
f.write('开始监听 客户端 %s:%s \n' % (addr[0], addr[1]))
print('开始监听 客户端 %s:%s' % (addr[0], addr[1]))
try:
conn.setsockopt(SOL_SOCKET, SO_KEEPALIVE, True)
conn.ioctl(SIO_KEEPALIVE_VALS, (1, 1 * 1000, 1 * 1000))
while True:
try:
# 接收消息
res = conn.recv(1024)
print(res)
except Exception as e:
with open('smartlabdemo/utils/tcpsocket.log', 'a') as f:
f.write('客户端 %s:%s 断开连接\n' % (addr[0], addr[1]))
print('客户端 %s:%s 断开连接' % (addr[0], addr[1]))
conn.close()
print(e)
break
except Exception as e:
print(e)
finally:
conn.close()
with open('smartlabdemo/utils/tcpsocket.log', 'a') as f:
f.write('客户端 %s:%s 协程结束\n' % (addr[0], addr[1]))
print('协程结束')
if __name__ == '__main__':
while True:
try:
serve = TCPserver()
serve.server(host, port)
except Exception as e:
with open('smartlabdemo/utils/tcpsocket.log', 'a') as f:
f.write('TCPsocket出错,等待重启socket....\n')
print('TCPsocket出错,等待重启socket....')
continue