服務端:dom
import socketserver
# import randomsocket
class MyServer(socketserver.BaseRequestHandler):code
def setup(self):
passserver
def handle(self):
conn = self.request
msg = "hello world!"
conn.send(msg.encode())
while True:ip
data = conn.recv(1024)
print(data.decode())input
if msg == b'exit':
break
msg_input = input("請輸入發送的消息:")
conn.send(msg_input.encode())
# conn.send(str(random.randint(1,1000)).encode())
conn.close()it
def finish(self):
passclass
if __name__ == "__main__":
server = socketserver.ThreadingTCPServer(("127.0.0.1",9999),MyServer)
server.serve_forever()import
客戶端:cli
import socket
client = socket.socket()
ip_port = ("127.0.0.1",9999)
client.connect(ip_port)
while True:
data = client.recv(1024)
print(data.decode())
msg_input = input("請輸入發送的消息:")
client.send(msg_input.encode())
if msg_input == "exit":
break
# data = client.recv(1024)
# print(data.decode())