首页 > 解决方案 > Ruby 客户端和 Python 服务器在交换时未收到完整消息

问题描述

我正在尝试建立客户端-服务器通信。客户端是用 Ruby 编写的,而服务器是用 Python 编写的。

客户端.rb

require 'socket'

hostname = 'localhost'
port = 7778

s = TCPSocket.open(hostname, port)
s.write("2020-06-25T11:11:00+00:00 5  127.0.0.1 printer: event")


while line = s.gets
puts line.chop
end

s.close()

ruby 客户端将日志发送到 Python 服务器并尝试将其接收回来。 服务器.py

import socket

#Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#bind the socket to the port - tuple
server_address = ('localhost', 7778)
print('starting up on %s port %s' %server_address)
sock.bind(server_address)
#Listen for incoming connections
sock.listen(1)

while True:
   print('waiting for a connection')
   connection, client_address = sock.accept()
   while True:
      data = connection.recv(1024)
      print('received "%s"' % data)
      if data:
         print('sending data back to the client')
         connection.send(data)
      else:
         print('no more data from', client_address)
         break
   connection.close()

日志被发送到python服务器,当python服务器将其发回时。当 ruby​​ 客户端收到它时,它不会收到完整的日志。例子:

2020-06-25T11:11:00+00:00 5  127.0.0.1 printer: eve

我认为这是因为 TCP 是一种流协议,我们永远不知道是否每次都能获得完整的消息。

您能否为我的客户端和服务器提出一个解决方案,以便我可以确保他们始终收到彼此之间的完整消息?如果有人能提供帮助,我将不胜感激。

标签: pythonrubyclient-server

解决方案


所以问题是你假设接收到的数据有一个换行符 - 但是你发送的数据不会被一个新行终止。

s.write("2020-06-25T11:11:00+00:00 5 127.0.0.1 printer: event")不会用换行符写入字符串 - 你应该使用puts IO#puts

s.gets将返回数据,因为套接字在发送数据后被 python 服务器关闭。所以甚至gets说它会从套接字读取下一行,实际上它只是读取套接字关闭后缓冲区中剩余的内容。

line.chop将删除最后一个字符,您在这里使用它来删除换行符(假设它有一个 from gets)。但是,由于没有换行符,它将删除最后一个字符。

所以解决方法是在 ruby​​ 客户端中替换s.writes.puts.


推荐阅读