Skip to content

Instantly share code, notes, and snippets.

@h2suzuki
Last active July 12, 2017 08:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h2suzuki/71c1487140bea95dae2054b9626dfa39 to your computer and use it in GitHub Desktop.
Save h2suzuki/71c1487140bea95dae2054b9626dfa39 to your computer and use it in GitHub Desktop.
import zmq
import numpy as np
import json
# ZeroMQ のバックグラウンド・スレッドのコンテキスト
context = zmq.Context()
# このサーバは、ポート5556で待ちます
socket = context.socket(zmq.REQ)
socket.bind("tcp://*:5556")
# 送信するデータの生成:2行3列の整数配列
M = np.asarray([[0,1,2],[2,1,0]])
# M をシリアライズ
dtype = str(M.dtype).encode('utf-8')
shape = json.dumps(M.shape).encode('utf-8')
data = M.tostring('C')
# マルチパートメッセージとして送信
socket.send_multipart([dtype, shape, data])
print("Request:\n{} sent".format(M))
# 計算結果を受け取る
[dtype2, shape2, data2] = socket.recv_multipart()
# Numpy Array にデシリアライズ
N = np.frombuffer(data2, dtype=dtype2.decode('utf-8'))
N.shape = json.loads(shape2.decode('utf-8'))
print("Reply:\n{} received".format(N))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment