服务端:
from socket import *
from threading import Thread
def communicate(conn):
while True:
try:
data = conn.recv(1024)
if not data: break
conn.send(data.upper())
except ConnectionResetError:
break
conn.close()
def server(ip, port):
server = socket(AF_INET, SOCK_STREAM)
server.bind((ip, port))
server.listen(5)
while True:
conn, addr = server.accept()
t = Thread(target=communicate, args=(conn,))
t.start()
server.close()
if __name__ == '__main__':
server('127.0.0.1', 8081)
多个客户端:
from socket import *
client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8081))
while True:
msg = input('>>: ').strip()
if not msg: continue
client.send(msg.encode('utf-8'))
data = client.recv(1024)
print(data.decode('utf-8'))
client.close()
- 基于线程池实现
服务端:
from concurrent.futures import ThreadPoolExecutor
from socket import *
def communicate(conn):
while True:
try:
data = conn.recv(1024)
if not data: break
conn.send(data.upper())
except ConnectionResetError:
break
conn.close()
def server(ip, port):
server = socket(AF_INET, SOCK_STREAM)
server.bind((ip, port))
server.listen(5)
while True:
conn, addr = server.accept()
pool.submit(communicate, conn)
server.close()
客户端同上
标签:socket,server,并发,import,close,接字,多线程,data,conn From: https://www.cnblogs.com/xiao01/p/18049762