一个基于multiprocessing的Server-Client实例

import multiprocessing
import time
import sys
import os

class MyServer(multiprocessing.Process):
    def __init__(self, c2s, s2c):
        multiprocessing.Process.__init__(self)
        self.c2s = c2s
        self.s2c = s2c
    
    def run(self):
        print('%s initialized' % multiprocessing.current_process().name)
        while True:
            msg = self.c2s.get()
            if msg['op'] == 'order':
                print('Server: Received an order: %s.' % msg['content'])
                self.s2c.put({'op':'ok'})
            elif msg['op'] == 'chat':
                print('Server: I am Server! I am replying to 【%s】' % msg['content'])
                self.s2c.put({'op':'ok'})
            elif msg['op'] == 'close':
                print('Server: Closing...')
                self.s2c.put({'op':'close'})
                break
            time.sleep(0.5)

class MyClient(multiprocessing.Process):
    ops = ['order', 'close', 'chat', 'ok']

    def __init__(self, c2s, s2c, fn):
        multiprocessing.Process.__init__(self)
        self.c2s = c2s
        self.s2c = s2c
        self.fn = fn
    
    def run(self):
        sys.stdin = os.fdopen(self.fn)
        print('%s initialized' % multiprocessing.current_process().name)
        while True:
            inp = input('>')
            inp = inp.split(':')
            if len(inp)==2 and inp[0] in self.ops:
                self.c2s.put({'op':inp[0],'content':inp[1]})
            msg = self.s2c.get()
            if msg['op']=='close':
                break
            time.sleep(0.5)

if __name__ == '__main__':
    c2s = multiprocessing.Queue()
    s2c = multiprocessing.Queue()
    server = MyServer(c2s, s2c)
    server.daemon = True
    server.start()
    fn = sys.stdin.fileno()
    client = MyClient(c2s, s2c, fn)
    client.daemon = False
    client.start()

    server.join()
    client.join()

思路

  1. 一个服务进程,一个客户进程,通过队列进行通信。
  2. 客户进程接收用户消息,并向服务进程发送消息。服务进程根据消息中的’op’对’content’做相应的处理。
  3. 用户输入格式为:[op:content],进程间传递的消息如下:
{'op':'xxx', 'content':'xxx'}

运行结果

MyServer-1 initialized
MyClient-2 initialized
>chat:hello
Server: I am Server! I am replying to 【hello】
>order:sing a song
Server: Received an order: sing a song.
>close:.
Server: Closing...

关键点

  1. multiprocessing的使用,如果直接用Process类的话,需要传入一个target函数,如果用现在这种方式实现的话,就写在run方法里面
  2. 要实现在client里输入,必须要用到下面这句,否则会出错
sys.stdin = os.fdopen(self.fn)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值