一个简易的Python多线程服务器可以同时连接多个客户端并接收客户端传入的信息,下面看下具体实现
import socket
import threading
def deal_client(newSocket: socket.socket, addr):
while True:
data = newSocket.recv(1024)
if data:
print("%s %s" % (str(addr), data))
else:
print("client [%s] exit" % str(addr))
newSocket.close()
break
def main():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("", 8080))
server.listen(10)
print("server is running!")
while True:
newSocket, addr = server.accept()
print("client [%s] is connected!" % str(addr))
client = threading.Thread(target=deal_client, args=(newSocket, addr))
client.start()
if __name__ == '__main__':
main()