[zeromq-dev] ZMQ.Poller in Java: how to do timeout check for REQ/REP?

Mikko Koppanen mikko.koppanen at gmail.com
Tue Sep 6 18:30:50 CEST 2011


2011/9/6 Igor 'Lo' (И.L.) <bombsiteunrested at gmail.com>:
> Hi all.
>
> I have ZMQ.REP socket sitting in some unstable C++ application, so
> Java client (doing ZMQ.REQ) can occasionally hang on socket.recv(),
> blocking the application.
> What I want is to have a recv() timeout of two seconds, returning an
> error if other party didn't either responds all all (TCP error on
> connection, adopted via LINGER) or responce time is bigger than 2
> seconds (have poll() to timeout after 2 seconds waiting).
>
> Following code does not work (hangs at polling):
>
> package TestPack;
> import java.util.ArrayList;
> import java.util.List;
> import java.io.*;
> import java.util.*;
> import java.math.BigInteger;
>
> import org.zeromq.ZMQ;
> import org.msgpack.*;
>
> class TestPack {
>        private static void doTest(String tester)
>        {
>                byte[] raw = MessagePack.pack(tester);
>
>                ZMQ.Context context = ZMQ.context(1);
>                ZMQ.Socket jsocket = context.socket(ZMQ.REQ);
>                jsocket.setLinger(0);
>                jsocket.connect ("tcp://localhost:1234");
>                jsocket.send(raw, 0);
>
>                ZMQ.Poller it = context.poller(1);
>                it.register(jsocket, ZMQ.Poller.POLLIN);
>
>                System.out.println("Started polling");
>                boolean got = false;
>                it.poll(); // <--- hangs here.
>                System.out.println("Done polling");
>                if (it.pollin(0)) {
>                    byte[] reply = jsocket.recv(0);
>                    String decode = new String(reply,0,reply.length-1);
>                    System.out.println(decode);
>                    got = true;
>                }
>                if (got == false) {
>                    System.out.println("Received nothing");
>                }
>                jsocket.close();
>        }
>
>        public static void main(String[] args)
>        {
>          doTest("hello world");
>        }
> }
>

Hi,

try calling setTimeout for the poll in java code. The default
behaviour is to block until there is activity in the socket:

https://github.com/zeromq/jzmq/blob/master/src/org/zeromq/ZMQ.java#L1147

-- 
Mikko Koppanen



More information about the zeromq-dev mailing list