socketserver 多进程、多线程应用实例

1、线程池,ThreadingTCPServer

#coding=utf-8
'''
可并发,客户端互不影响,可以保持长连接,客户端发送消息 也不要求加 \r\n
'''

#线程池(windows 可运行)

from socketserver import *
import threading

class MyTCPHandler(BaseRequestHandler):

    def handle(self):
        while 1:
            self.data=self.request.recv(1024).strip()

            cur_thread=threading.current_thread()
            print('cur_thread.name:',cur_thread.name)

            #if not self.data:
            if self.data=='bye':
                print('客户端退出:',self.client_address[0])
                break
            print('客户端IP:%s:%s,内容:%s'%(self.client_address[0],self.client_address[1],self.data.decode()))

            self.request.sendall(self.data.upper())

if __name__=='__main__':
    print('监听开始了。。。。')
    server=ThreadingTCPServer(('127.0.0.1',9977),MyTCPHandler)
    server.serve_forever()

client 客户端程序:

#coding=utf-8
'''
client
'''
from socket import *

sk=socket()

sk.connect(('127.0.0.1',9977))
while 1:
    sk.settimeout(50)

    print('sending...now....')
    s=input('输入:')
    sk.send(s.encode())
    if s=='bye':
        break

    print(sk.recv(1024).decode())

sk.close()

2、ThreadingMixIn与TCPServer

#coding=utf-8
'''
貌似是一个真正的并发
客户端不等待,互不影响,linux下运行
'''
from socketserver import TCPServer,StreamRequestHandler,ThreadingMixIn

import time
class Server(ThreadingMixIn,TCPServer):
    pass

class MyHandler(StreamRequestHandler):

    def handle(self):
        addr=self.request.getpeername()
        print('来自客户端:',addr)
        print('from address:',self.client_address)
        data=self.rfile.readline().strip()
        print('*'*10)
        print(type(data))
        print(data.decode())
        #if data.decode()=='bye' or not data:
        #    break
        time.sleep(0.1)
        if data:
            self.wfile.write('服务器回复的消息'.encode('utf-8'))

if __name__=='__main__':

    sever=Server(('127.0.0.1',9966),MyHandler)

    sever.serve_forever()

client客户端程序:

#coding=utf-8
from socket import *

addr=('127.0.0.1',9966)
print('addr:',addr)

while 1:
    
    sk=socket(AF_INET,SOCK_STREAM)
    sk.connect(addr)

    print('send begin...')
    data=input('please input something:')
    sk.send((data+'\r\n').encode('utf-8'))
    if data=='bye'or not data:
        break

    print('recv begin....')
    print(sk.recv(1024))
    print('recv over...')
sk.close()

3、

#coding=utf-8
'''
貌似是串行,多连接,会等待1发送消息完成,才会处理2
'''
#from socketserver import TCPServer,ForkingMixIn,StreamRequestHandler
from socketserver import *
import time

class Server(TCPServer,ForkingMixIn):
    pass

class MyHandler(StreamRequestHandler):
    def handle(self):
        addr=self.request.getpeername()
        print('connect from :',addr)
        try:
            data=self.rfile.readline().strip()##客户端传的数据必须加上'\r\n'结尾
            print('data:',data)
            time.sleep(0.1)
        except:
            print('jie shou bao cuo le..')
        if data:
            self.wfile.write('this is a server message'.encode('utf-8'))

if __name__=='__main__':
    
    server=Server(('127.0.0.1',9900),MyHandler)#连接是接收一次,关闭一次,每次传数据都要重新建立连接
    print('server object:',server)
    server.serve_forever()

client 客户端程序:

from socket import *

addr=('127.0.0.1',9900)

while 1:
    sk=socket(AF_INET,SOCK_STREAM)  #注意每次都要创建连接,服务端收一次数据就会关闭连接
    sk.connect(addr)
    data=input('input sth:')
    if not data:
        break
    sk.send((data+'\r\n').encode()) #发送数据必须加\r\n结尾
    data=sk.recv(1024)
    if not data:
        break
    print(data.strip())
    sk.close()

 4、最基础的TCPServer小实例

#coding=utf-8

from socketserver import TCPServer,StreamRequestHandler as srh
import time
import traceback

class MyHandler(srh):
    def handle(self):
        print('client address:',self.client_address)
        try:
            print('sever recv begin...')
            dd=self.rfile.readline() #客户端发送一定加入\r\n结尾,否则会卡死
            print('received data is:',dd)
        
            self.wfile.write('server send message!!'.encode())
            #self.wfile.write('%s,%s'%(self.data,time.strf('%Y-%m-%d %H:%M:%S',time.time())))
        except:
            traceback.print_exc()
            print('baocuo ru shang')

server=TCPServer(('127.0.0.1',21567),MyHandler)  #每次发送请求后自动关闭连接,不能长连接
server.serve_forever()

client客户端程序:

 

from socket import *

addr=('127.0.0.1',21567)

while 1:
    sk=socket(AF_INET,SOCK_STREAM)  #注意每次都要创建连接,服务端收一次数据就会关闭连接
    sk.connect(addr)
    data=input('input sth:')
    if not data:
        break
    sk.send((data+'\r\n').encode()) #发送数据必须加\r\n结尾
    data=sk.recv(1024)
    if not data:
        break
    print(data.strip())
    sk.close()

 

posted @ 2019-03-05 18:55  小金儿  阅读(729)  评论(0编辑  收藏  举报