服务端
import socketserver
class MyServer(socketserver.BaseRequestHandler):
def handle(self):
print('conn is ',self.request) #conn
print('addr is ',self.client_address) #addr
while True:
#解决强制关闭客户端导致服务端报错问题
try:
# 收消息
data = self.request.recv(1024)
if not data:break
print('收到客户端的消息是', data)
# 发消息
self.request.sendall(data.upper())
except Exception as e:
print(e)
break#跳出真个循环
print(__name__)
if __name__ == '__main__':
s=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyServer)
# s = socketserver.ForkingTCPServer(('127.0.0.1', 8080), MyServer)#多进程
![](https://user-gold-cdn.xitu.io/2018/3/8/1620436a4e1d1376?w=864&h=540&f=png&s=17495)
s.serve_forever()
复制代码
客户端1
from socket import *
import struct
ip_port = ('127.0.0.1',8080)
back_log=5
buffer_size=1024
tcp_client = socket(AF_INET,SOCK_STREAM)
tcp_client.connect(ip_port)
while True:
msg = input('>>:').strip()
if not msg:continue
if msg == 'quit':break
tcp_client.send(msg.encode('utf-8'))
data = tcp_client.recv(buffer_size)
print('收到服务端发来的消息:',data.decode('utf-8'))
tcp_client.close()
复制代码
客户端2
from socket import *
import struct
ip_port = ('127.0.0.1',8080)
back_log=5
buffer_size=1024
tcp_client = socket(AF_INET,SOCK_STREAM)
tcp_client.connect(ip_port)
while True:
msg = input('>>:').strip()
if not msg:continue
if msg == 'quit':break
tcp_client.send(msg.encode('utf-8'))
data = tcp_client.recv(buffer_size)
print('收到服务端发来的消息:',data.decode('utf-8'))
tcp_client.close()
复制代码
运行结果