Python——socketserver编程(客户端/服务器)

时间:2021-06-12 23:58:13

一、socketserver是标准库中的高级模块,它的目标是简化很多多样板代码,是创建网络客户端和服务器所必须的代码。(事件驱动)

二、模块类

BaseServer :包含核心服务器功能和mix-in类的钩子,可以用TCPServer或UDPserver创建类的实例

TCPserver/UDPserver:基础的TCP/UDP服务器

UnixStereamServer/UnixDatagramServer:基于文件的TCP/UDP服务器

ForkingMixIn/ThreadingMixIn:核心派出或线程功能

ForkingTCPServer/ForkingUDPServer:ForkingMixIn和TCPServer/UDPServer的组合

ThreadingTCPServer/ThreadUDPServer:ThreadingMixIn和TCPServer/UDPServer的组合

BaseRequestHandler:处理服务请求的核心功能

StreamRequestHandler/DatagramRequestHandler:实现TCP/UDP服务器的服务处理

三、TCP服务器

from socketserver import TCPServer as TCP, StreamRequestHandler as SRH
from time import ctime
Host = ""
Post = 21567
Addr = (Host,Post)
class MyRequestHandler(SRH):
    def handle(self):
        print ('...connectde from:',self.client_address)
        self.wfile.writr('[%s]%s'%(ctime(),self.rfile.readline()))
        
tcpServ = TCP(Addr,MyRequestHandler)
print ('waiting for connection ...')
tcpServ.server_forever()

四、TCP客户端

from socket import *
Host = 'localhost'
Post = 21567
Bufsiz = 1024
Addr =(Host,Post)
while True:
    tcpCliSock = socket(AF_INET,SOCK_STREAM)
    tcpCliSock.connect(Addr)
    data = raw_input('>')
    if not data:
        break
    tcpCliSock.Send('%s\r\n'%data)
    data = tcpCliSock.recv(Bufsiz)
    if not data:
        break
    print (data.strip())
    tcpCliSock.close()