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( )
思路
一个服务进程,一个客户进程,通过队列进行通信。 客户进程接收用户消息,并向服务进程发送消息。服务进程根据消息中的’op’对’content’做相应的处理。 用户输入格式为:[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.. .
关键点
multiprocessing的使用,如果直接用Process类的话,需要传入一个target函数,如果用现在这种方式实现的话,就写在run 方法里面 要实现在client里输入,必须要用到下面这句,否则会出错
sys. stdin = os. fdopen( self. fn)