40---基于TCP协议实现并发的三种方式

一 基于TCP协议socketsever模块实现并发编程

  • 服务端
import socketserver
class MyRequestHandle(socketserver.BaseRequestHandler):
    def handle(self):
        print(self.client_address)
        while True:
            try:
                msg = self.request.recv(1024)
                if not msg:break
                self.request.send(msg.upper())
            except Exception:
                break
        self.request.close()

s = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyRequestHandle)
s.serve_forever()
  • 客户端
import socket
client = socket.socket(-1,-1)
client.connect(('127.0.0.1',8080))
while True:
    msg = input('》》').strip()
    if len(msg) == 0:continue
    if msg == 'q':break
    client.send(msg.encode('utf-8'))
    data = client.recv(1024)
    print(data.decode('utf-8'))

二 基于TCP协议多进程实现并发

  • 服务端
import socket
from threading import Thread
sever = socket.socket()
sever.bind(('127.0.0.1',8081))
sever.listen(5)

def talk(conn):
    while True:
        try:
            data = conn.recv(1024)
            if not data:
                break
            conn.send(data.upper())
        except Exception:
            break
    conn.close()
    
# 多进程下基于TCP并发,进程的启动一定要放在main中
if __name__ == '__main__':

    while True:
        conn,addr = sever.accept()
        t = Thread(target=talk,args=(conn,))
        t.start()
  • 客户端
import socket

client = socket.socket()
client.connect(('127.0.0.1',8081))

while True:
    msg = input('>>').strip()
    if not msg:
        continue
    if msg == 'q':
        break
    client.send(msg.encode('utf-8'))
    data = client.recv(1024)
    print(data.decode('utf-8'))
client.close()

三 基于TCP协议多线程实现并发

  • 服务端
import socket
from threading import Thread
sever = socket.socket()
sever.bind(('127.0.0.1',8081))
sever.listen(5)

def talk(conn):
    while True:
        try:
            data = conn.recv(1024)
            if not data:
                break
            conn.send(data.upper())
        except Exception:
            break
    conn.close()

while True:
    conn,addr = sever.accept()
    t = Thread(target=talk,args=(conn,))
    t.start()
  • 客户端
import socket

client = socket.socket()
client.connect(('127.0.0.1',8081))

while True:
    msg = input('>>').strip()
    if not msg:
        continue
    if msg == 'q':
        break
    client.send(msg.encode('utf-8'))
    data = client.recv(1024)
    print(data.decode('utf-8'))
client.close()
posted @ 2020-04-26 19:35  微信搜索-程序媛小庄  阅读(382)  评论(0编辑  收藏  举报