python-2.7ctypesnanomsg

Setting up socket timeout in nanomsg python


I am having trouble setting the timeout properly on nanomsg python in the PUSH/PULL schema. I use the set socket option function and passing in a ctype object. Both set_sock_options return a success. Am I missing something?

The sockets work to receive and send, but have an infinite timeout. When I use get_sock_option it returns the value I just set, so it seems my inputs have some sort of an effect.

NN_RCVTIMEO = 5
NN_SNDTIMEO = 4
NN_SOL_SOCKET = 0

message = ""

timeout = ctypes.create_string_buffer(b'500');

#Bind input socket
socket_in = nn_wrapper.nn_socket(AF_SP, PULL)
sucess = nn_wrapper.nn_setsockopt(socket_in, NN_SOL_SOCKET, NN_RCVTIMEO, timeout)
nn_wrapper.nn_bind(socket_in, 'tcp://127.0.0.1:64411')
time.sleep(0.2)

print("SUCESS?" + str(sucess))


#Send inquiry
socket_out = nn_wrapper.nn_socket(AF_SP, PUSH)
sucess = nn_wrapper.nn_setsockopt(socket_out, NN_SOL_SOCKET, NN_SNDTIMEO, timeout)
nn_wrapper.nn_connect(socket_out, 'tcp://127.0.0.1:64400')
time.sleep(0.2)

print("SUCESS?" + str(sucess))

nn_wrapper.nn_send(socket_out, b'HELLO',0)

#Received...
bytes, message = nn_wrapper.nn_recv(socket_in, 0)

nn_wrapper.nn_close(socket_in)
nn_wrapper.nn_close(socket_out)

Solution

  • Looks like when working with C function wrappers that take in arguments by reference(in this case an integer), you have to use the 'struct' module. This is how one would use the integer value 500 as a parameter for the nn_setsockopt() function:

    from struct import Struct
    from nanomsg import wrapper as nn_wrapper
    from nanomsg import Socket, PULL, PUSH, AF_SP
    import ctypes
    
    NN_RCVTIMEO = 5
    NN_SOL_SOCKET = 0
    
    INT_PACKER = Struct(str('i'))
    timeout = (ctypes.c_ubyte * INT_PACKER.size)()
    INT_PACKER.pack_into(timeout, 0, 500)
    
    socket_in = nn_wrapper.nn_socket(AF_SP, PULL)
    nn_wrapper.nn_bind(socket_in, 'tcp:///127.0.0.1:60000')
    nn_wrapper.nn_setsockopt(socket_in, NN_SOL_SOCKET, NN_RCVTIMEO, timeout)