Created
October 12, 2016 13:43
-
-
Save haburibe/476439dcad75d0c21c847650840f8c86 to your computer and use it in GitHub Desktop.
プロセス間でzeromqを介した通信を行うサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
# | |
# プロセス間でzeromqを介した通信を行うサンプル | |
# 参考: | |
# - http://zguide.zeromq.org/page:all#Ask-and-Ye-Shall-Receive | |
# - https://pyzmq.readthedocs.io/en/latest/api/zmq.html | |
# | |
import os | |
import time | |
import zmq | |
def server(): | |
'''サーバーを作成し、クライアントと送受信を行う | |
''' | |
context = zmq.Context() | |
socket = context.socket(zmq.REP) | |
socket.bind('tcp://*:5555') | |
# recv_json()でJSONを受け取る | |
# 他にrecv_multipart(), recv_pyobj(), recv_string()など | |
request = socket.recv_json() | |
time.sleep(1) | |
print('Received request: {}'.format(request)) | |
response = { | |
'greeting': 'Hello, {}'.format(request['name']), | |
} | |
socket.send_json(response) | |
def client(): | |
'''クライアントを作成し、サーバーと送受信を行う | |
''' | |
context = zmq.Context() | |
socket = context.socket(zmq.REQ) | |
socket.connect('tcp://localhost:5555') | |
request = {'name': 'Goro'} | |
print('-- Sending request: {}'.format(request)) | |
# send_json()でJSONを送信する | |
# 他にsend_multipart(), send_pyobj(), send_string()など | |
socket.send_json(request) | |
response = socket.recv_json() | |
print('-- Received reply [ {} ]'.format(response)) | |
def main(): | |
# forkしてサーバーとクライアントをそれぞれ起動する | |
if os.fork(): | |
server() | |
else: | |
client() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment