码迷,mamicode.com
首页 > 编程语言 > 详细

python3-TCP服务器和客户端(socketserver类)

时间:2018-11-21 21:14:44      阅读:673      评论:0      收藏:0      [点我收藏+]

标签:import   host   amr   ==   bytes   127.0.0.1   服务器端   time()   serve   

#!/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类)

标签:import   host   amr   ==   bytes   127.0.0.1   服务器端   time()   serve   

原文地址:http://blog.51cto.com/13959448/2319841

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!