服務(wù)端
import socketserver
class MyRequestHandle(socketserver.BaseRequestHandler): #定義一個(gè)類,引用sockerserver的基類socketserver.BaseRequestHandler
def handle(self):
print(self.request) # 此步,相當(dāng)于tcp套接字下面2步
# conn, client_addr = phone.accept()
# print(client_addr)
while True:
try:
cmd = self.request.recv(1024) # self.request 相當(dāng)于conn
if cmd == 0: break
self.request.send(cmd.upper())
except Exception:
break
s = socketserver.ThreadingTCPServer(('127.0.0.1', 8899), MyRequestHandle)
s.serve_forever()
客戶端 (開啟多個(gè)客戶端)
from socket import *
client=socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8899))
while True:
cmd=input('小寫轉(zhuǎn)換大寫>>>>'.strip())
if len(cmd)==0:continue
client.send(cmd.encode('utf-8'))
msg=client.recv(1024)
print(msg.decode('utf-8'))
執(zhí)行如下
客戶端1:
請輸入命令>>:ls
LS
請輸入命令>>:
客戶端2:
請輸入命令>>:hello
HELLO