亲宝软件园·资讯

展开

python网络编程:socketserver使用方法 python网络编程:socketserver的基本使用方法实例分析

随风行云 人气:0

本文实例讲述了python网络编程:socketserver的基本使用方法。分享给大家供大家参考,具体如下:

本文内容:

首发时间:2018-03-21


也可以使用socketserver来创建socket


socketserver的介绍:


socketserver的使用:

服务端:

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()

socketserver的异步服务端:

多线程: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程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论