(1)client客户端:
import socket
sk = socket.socket()
sk.connect( ("127.0.0.1",9000))
while True:
sk.send(b'hello')
msg = sk.recv(1024)
print(msg)
sk.close()
(2)server服务端:
import socketserver
# 自定义一个类 MyServer
class MyServer(socketserver.BaseRequestHandler):
# handle 方法是每当有一个客户端发起connect来接之后,自动执行handle
def handle(self):
print("--->执行这句话")
# print(self.request) 等于 conn
# print(self.client_address) 等于 addr
conn = self.request
while True:
msg = conn.recv(1024).decode("utf-8")
print(msg)
conn.send(msg.upper().encode("utf-8"))
# ip 端口号 | 自定义类
server = socketserver.ThreadingTCPServer(("127.0.0.1",9000),MyServer)
# 循环调用
server.serve_forever()