# 服务端必须满足至少三点:
# 1. 绑定一个固定的ip和port
# 2. 一直对外提供服务,稳定运行
# 3. 能够支持并发
"""
这个程序是基于TCP协议通信,并且实现了并发
"""
###服务端程序
import socketserver
# 自定义类用来处理通信循环
class MyTCPhanler(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
data = self.request.recv(1024)
if len(data) == 0: break # 针对linux系统
print('-->收到客户端的消息: ', data)
self.request.send(data.upper())
except ConnectionResetError:
break
self.request.close()
if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(('127.0.0.1', 8081), MyTCPhanler)
server.serve_forever() # 链接循环
##客户端程序
from socket import *
client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8081))
# 通信循环
while True:
msg = input('>>: ').strip() # msg=''
if len(msg) == 0: continue
client.send(msg.encode('utf-8')) # client.send(b'')
# client.send('hello'.encode('utf-8')) #client.send(b'')
# print('has send')
data = client.recv(1024)
# print('has recv')
print(data)
client.close()