python3-TCP服務器和客戶端(socketserver類)
阿新 • • 發佈:2018-11-21
env amr rip address ctrl+c utf-8 request ctrl reat
#!/usr/bin/env python3
import socket
import sys
HOST="localhost"
PORT=21200
ADDR=(HOST,PORT)
# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# 連接服務器
sock.connect(ADDR)
data=input(‘==>‘)
sock.sendall(bytes(data + "\n", "utf-8"))
# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")
print("Sent: {}".format(data))
print("Received: {}".format(received))
#!/usr/bin/env python3
import socketserver
from time import ctime
HOST=‘‘
PORT=21200
ADDR=(HOST,PORT)
class MyTCPHandler(socketserver.StreamRequestHandler):
def handle(self):
print("接受{0}連接...".format(self.client_address))
self.data = self.rfile.readline().strip()
print("{} 發來消息:".format(self.client_address[0]))
print(self.data)
# self.wfile是一個類似文件的對象,用於寫回客戶端
self.wfile.write(bytes("{0}:{1} ".format(ctime(),self.data),‘utf-8‘))
if __name__ == "__main__":
# Create the server, binding to localhost on port 9999
with socketserver.TCPServer(ADDR, MyTCPHandler) as server:
print("等待連接...")
#激活服務器,直到按ctrl+c退出
server.serve_forever()
bogon:python3 myhaspl$ python3 1-c.py
==>hhhh
Sent: hhhh
Received: Sun Sep 16 12:47:01 2018:b‘hhhh‘
下面是服務器端運行狀態:
等待連接...
接受(‘127.0.0.1‘, 50751)連接...
127.0.0.1 發來消息:
b‘hi‘
接受(‘127.0.0.1‘, 50752)連接...
127.0.0.1 發來消息:
b‘hhhh‘
python3-TCP服務器和客戶端(socketserver類)