1

I had created a zmq.SUB client to receive data from server when it can get data.

client.py


import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.subscribe("")
socket.connect("tcp://localhost:9000")

while True:
    print(socket.recv_string())

The problem is my server need to send some data only once and then need to quickly close.And then reopen it,send data and then close repeatly those steps forever.But the client can't get any data from server, can anyone have some solutions in my special scenarios?

server.py


import zmq
context = zmq.Context.instance()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:9000")
socket.send_string(f"Hello")

operation

python client.py  
python server.py  
python server.py  
python server.py  
jett chen
  • 1,067
  • 16
  • 33

1 Answers1

1

i changed the code a bit and it works now, i think that it didn't work because you send the message instantly.

Server.py

import zmq
import time
context = zmq.Context.instance()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:9000")

input("press enter to send message...")
socket.send_string(f"Hello")

client.py

import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect("tcp://127.0.0.1:9000")
socket.subscribe("")

while True:
    print(socket.recv_string())

now just run

python client.py

and then

python server.py

and press enter (not instantly wait for at least a quarter of a second!)

  • Not good method, Is there have any method that I can know what client had connected or the server had send message successfully to client? – jett chen Jun 29 '21 at 02:51
  • your problem was, that you couldn't receive data; because zmq is asynchronous which means that before sending something you need to wait a couple of milliseconds until everything is initialized. i don't know if its possible to do what you want to do with zmq – GOD is dead Jun 29 '21 at 11:30
  • Yes zmq is asynchronous, but I need know what time server had accpeted new client, or the client had successfully connected server, any ideas you have? – jett chen Jun 30 '21 at 00:38
  • i think you should close this question and open a new one where you ask that question – GOD is dead Jun 30 '21 at 13:20
  • 你说得是啊,我不用这个方法了,换个能用的了 – jett chen Jul 02 '21 at 10:47
  • 好的,希望我至少可以帮助你一点 i don't speak Chinese though – GOD is dead Jul 05 '21 at 22:41
  • Fine, thanks for you help,see you later in the future. – jett chen Jul 06 '21 at 03:23