python - 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 是一种流协议,我们永远不知道是否每次都能获得完整的消息。
您能否为我的客户端和服务器提出一个解决方案,以便我可以确保他们始终收到彼此之间的完整消息?如果有人能提供帮助,我将不胜感激。
解决方案
所以问题是你假设接收到的数据有一个换行符 - 但是你发送的数据不会被一个新行终止。
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.write
为s.puts
.
推荐阅读
- java - 如何声明每个实现 Comparable 的 Java 对象列表
- javascript - 按超过 2 层深度的条件合并嵌套对象
- javascript - 如何从 JavaScript 执行下载的安装程序
- c - 在 C 语言中取消引用指向指针等的指针的指针
- docker - 无法在 gcloud 上部署容器
- php - 如何减去两个日期并以分钟为单位获得差异 PHP
- google-apps-script - Google 表格自动将自定义范围发送到电子邮件
- javascript - 使用 Create React App 在开发中代理
- php - 如何通过在我的后端页面中循环获取响应数据
- java - 如何在 Spring Security 中使用内置 X-Auth-Token 而不是 Spring Session Http Cookie