Python-SocketServer

建立一个SocketServer,首先要创建一个请求处理类,这个类要继承BaseRequestHandler,还要重写父类里handle()方法,handle()方法在父类中为空的

然后实例化TCPServer,并且传递server ip和创建的请求处理类给这个TCPServer

服务器端

# -*-coding:utf-8-*-
__author__ = "MuT6 Sch01aR"

import socketserver,socket

class MyTCPHandler(socketserver.BaseRequestHandler): #创建请求处理类,继承BaseRequestHandler
    def handle(self): #重写父类里handle()方法
        while True:
            try:
              self.data = self.request.recv(1024).strip()
              print('来自',self.client_address[0])
              print(self.data)
              self.request.send(self.data)
            except socket.error:
                print('客户端断开连接')
                break

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler) #实例化TCPServer
    # server = socketserver.UDPServer((HOST, PORT), MyTCPHandler) #实例化UDPServer
    server.serve_forever() #处理多个请求,一直执行
    # servser.handle_request() #只处理一个请求

客户端

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import socket

s = socket.socket()
s.connect(('localhost', 9999))
while True:
    cmd = input('>>>:').strip()
    if len(cmd) == 0:continue
    s.send(cmd.encode('utf-8'))
    print(s.recv(1024))
s.close()

运行结果

但是还是不能实现多个连接进行socket通信

socketserver多并发

服务器端

# -*-coding:utf-8-*-
__author__ = "MuT6 Sch01aR"

import socketserver,socket

class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        while True:
            try:
              self.data = self.request.recv(1024).strip()
              print('来自',self.client_address[0])
              print(self.data)
              self.request.send(self.data)
            except socket.error:
                print('客户端断开连接')
                break

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
    server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) #通过多线程实现TCPServer多并发
    #server = socketserver.ForkingTCPServer((HOST, PORT), MyTCPHandler) #通过多进程实现TCPServer多并发
    #server = socketserver.ThreadingUDPServer((HOST, PORT), MyTCPHandler) #通过多线程实现UDPServer多并发
    #server = socketserver.ForkingUDPServer((HOST, PORT), MyTCPHandler) #通过多线程实现UDPServer多并发
    server.serve_forever()

windows系统还不能用多进程进行socketserver多并发

客户端

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import socket

s = socket.socket()
s.connect(('localhost', 9999))
while True:
    cmd = input('>>>:').strip()
    if len(cmd) == 0:continue
    s.send(cmd.encode('utf-8'))
    print(s.recv(1024))
s.close()

 

posted @ 2018-02-17 21:19  Sch01aR#  阅读(163)  评论(0编辑  收藏  举报