我正在测试向外部系统发送一些简单的HTTP请求。虽然我已经成功地表明在功能上,当我发送20多个消息时,被测系统正在处理一条消息,但我遇到的故障似乎是由于未收到消息,而是系统本身出现了问题。
当前,我正在通过UDP发送消息,但想查看是否是导致丢失的原因,因此希望转换为通过TCP发送
通过UDP发送的代码
@when('{number_of_requests} HTTP requests are sent to it')
def step_impl(context, number_of_requests):
# Waiting for the service to be ready after restart
time.sleep(1)
# Get the Endpoint address and port from Config.py
UDP_IP = config.endpoint['host']
UDP_PORT = int(config.endpoint['port'])
context.messages_sent = []
# Setting up the socket to send the UDP datagrams
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setblocking(True)
# Getting the configured sub id header name
sub_id_header_name = get_subid_header_name()
context.subscribers = generate_subscribers(number_of_requests)
sock.sendto(bytes("xxx", "utf-8"), (UDP_IP, UDP_PORT))
for i in range(int(number_of_requests)):
# Generating a SPID
spid = encodespid("ab")
# Generating a SUB_ID
sub_id = context.subscribers[i]
# Setting up the whole message to be sent
message = small_message.format(spid, sub_id_header_name, sub_id)
# Sending the message
sock.sendto(bytes(message, "utf-8"), (UDP_IP, UDP_PORT))
context.messages_sent.append(spid)
# Closing the socket
sock.close()
要通过TCP发送的代码(到目前为止)
@when('{number_of_requests} HTTP requests are sent to it')
def step_impl(context, number_of_requests):
# Waiting for the service to be ready after restart
time.sleep(1)
# Get the Endpoint address and port from Config.py
TCP_IP = config.endpoint['host']
TCP_PORT = int(config.endpoint['port'])
context.messages_sent = []
# Setting up the socket to send the UDP datagrams
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setblocking(True)
# Getting the configured sub id header name
sub_id_header_name = get_subid_header_name()
context.subscribers = generate_subscribers(number_of_requests)
sock.send(bytes("xxx", "utf-8"), (TCP_IP, TCP_PORT))
for i in range(int(number_of_requests)):
# Generating a SPID
spid = encodespid("ab")
# Generating a SUB_ID
sub_id = context.subscribers[i]
# Setting up the whole message to be sent
message = small_message.format(spid, sub_id_header_name, sub_id)
# Sending the message
sock.send(bytes(message, "utf-8"), (TCP_IP, TCP_PORT))
context.messages_sent.append(spid)
# Closing the socket
sock.close()
正如您在上面看到的,在线阅读后,我已将所有对UDP的引用更改为TCP,并将Sendto转换为Send,这是通过TCP发送的正确方法。但是,这里似乎还缺少其他内容,因为它现在无法发送任何内容。
有关转换First代码块以使其能够发送TCP而不是UDP的最佳方法的任何帮助
答案 0 :(得分:1)
python中的套接字是根据linux套接字API建模的(请查看链接以了解有关套接字类型的差异以及linux API说什么的更多信息。)
另外,您似乎还没有阅读python中的套接字文档,因此请阅读it
现在您有问题要问,
您的问题如下,在两个示例中,您都使用socket.SOCK_DGRAM
代表数据报。它用于UDP等无连接协议。
对于TCP,您需要一个支持双向可靠的套接字类型(您将知道数据包是否丢失),即SOCK_STREAM
。但是因为它是可靠的,所以它必须是有状态的并且不能没有连接。
所以您必须
SOCK_STREAM
类型的套接字。# create socket of SOCK_STREAM type
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect to your server
sock.connect((TCP_IP, TCP_PORT))
# do the sending/receiving part
sock.sendall(b'Hello, world')
data = sock.recv(1024)
# close the connection
s.close()