Python 的 socket 与 多线程
server.py
import socket
import threading
def handle_client(c, addr):
print(addr, "connected.")
while True:
data = c.recv(1024)
if not data:
break
print((addr)," says:",data.decode('utf-8'))
c.sendall(data) # 重复发送消息
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("192.168.6.247", 1234))
s.listen(5)
while True:
c, addr = s.accept()
t = threading.Thread(target=handle_client, args=(c, addr))
t.start()
client.py
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
host = input("host:")
s.connect((host,1234)) # 仅可使用1234端口
msg = input("Send:")
s.sendall(msg.encode('utf-8'))
data = s.recv(1024)
print("Received:",data.decode('utf-8'))
可以开启多个客户端连接同一个服务器