在nanomsg python中设置套接字超时

时间:2018-01-15 12:46:23

标签: python-2.7 ctypes nanomsg

我无法在PUSH / PULL架构中的nanomsg python上正确设置超时。我使用set socket选项函数并传入一个ctype对象。 set_sock_options都返回成功。我错过了什么吗?

套接字用于接收和发送,但具有无限超时。当我使用get_sock_option时,它返回我刚设置的值,所以看起来我的输入有某种效果。

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)

2 个答案:

答案 0 :(得分:1)

看起来当使用C引用参数的C函数包装器(在本例中是一个整数)时,你必须使用' struct'模块。这就是如何使用整数值 500 作为 nn_setsockopt()函数的参数:

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)

答案 1 :(得分:1)

晚些时候参加聚会,希望对下一个家伙有帮助...

该库的作者已经想到了这些问题,并为套接字对象提供了一个set_int_option python。

这对我有用:

import nanomsg


class ManagementClient:
    def __init__(self, endpoint):
        self._client_socket = nanomsg.Socket(nanomsg.REQ)
        self._client_socket.set_int_option(nanomsg.SOL_SOCKET, nanomsg.RCVTIMEO, 5 * 1000)
        self._client_socket.connect("tcp://" + endpoint)