本文实例讲述了python网络编程:socketserver的基本使用方法。分享给大家供大家参考,具体如下:
首发时间:2018-03-21
也可以使用socketserver来创建socket
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
try:
while True:
self.data=self.request.recv(1024)
print("{} send:".format(self.client_address),self.data)
if not self.data:
print("connection lost")
break
self.request.sendall(self.data.upper())
except Exception as e:
print(self.client_address,"连接断开")
finally:
self.request.close()
def setup(self):
print("before handle,连接建立:",self.client_address)
def finish(self):
print("finish run after handle")
if __name__=="__main__":
HOST,PORT = "localhost",9999
server=socketserver.TCPServer((HOST,PORT),MyTCPHandler)
server.serve_forever()
import socket
client=socket.socket()
client.connect(('localhost',9999))
while True:
cmd=input("(quit退出) ").strip()
if len(cmd)==0:
continue
if cmd=="quit":
break
client.send(cmd.encode())
cmd_res=client.recv(1024)
print(cmd_res.decode())
client.close()
多线程:ThreadingTCPServer
多进程:ForkingTCPServer(Unix)
多线程版:
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
try:
while True:
self.data=self.request.recv(1024)
print("{} send:".format(self.client_address),self.data)
if not self.data:
print("connection lost")
break
self.request.sendall(self.data.upper())
except Exception as e:
print(self.client_address,"连接断开")
finally:
self.request.close()
def setup(self):
print("before handle,连接建立:",self.client_address)
def finish(self):
print("finish run after handle")
HOST,PORT = "localhost",9999
server=socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)#多线程版
server.serve_forever()
更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。