基本思想是每次有客户端请求服务的时候,服务器端的程序就创建一个新的线程专门服务于该客户端的服务请求。
服务器端server.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: 人海中的海盗
# 每次有客户端请求服务的时候,服务器端的程序就创建一个新的线程专门服务于该客户端的服务请求
from socket import *
import threading
# 服务器和客户端数据通信
def server_to_client(client_socket, addr):
while True:
try:
client_socket.settimeout(500)
buf = client_socket.recv(1024).decode()
print("server got msg from", str(addr[1]), buf)
client_socket.send('{} {}'.format(buf, str(addr[1])).encode())
except socket.timeout:
print('time out')
break
client_socket.close()
server_host = '127.0.0.1'
server_port = 9999
server = socket(AF_INET, SOCK_STREAM)
server.bind((server_host, server_port))
server.listen(5)
while True:
# 接受某客户端服务请求
client, address = server.accept()
print('Server connected by', address)
# 为该客户请求建立专有服务线程
thread = threading.Thread(target=server_to_client, args=(client, address))
# 启动线程,激活
thread.start()
客户端client.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: 人海中的海盗
import time
from socket import *
serverHost = '127.0.0.1'
serverPort = 9999
socket_client = socket(AF_INET, SOCK_STREAM)
socket_client.connect((serverHost, serverPort))
while True:
line = "client python"
socket_client.send(line.encode())
time.sleep(4)
data = socket_client.recv(1024).decode()
if not data:
break
print('Client received:', data)
socket_client.close()