【发布时间】:2017-02-12 18:57:42
【问题描述】:
我需要使用 python 将字符串发送到本地主机上的特定端口。
我可以通过在命令行上使用 socat 来实现这一点,如下所示:
cat <text file containing string to send> | socat stdin tcp-connect:127.0.0.1:55559
我不想将 socat 命令作为子命令运行,所以我想知道如何使用 python 模块使其工作。
我尝试使用套接字失败了。下面是我使用的一个脚本,它没有达到预期的效果。
import socket
HOST, PORT = "127.0.0.1", 55559
jsonString = '{"name":"VideoStreamStatus","parameters":{"name":"video_0_0"}}'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
print "Attempting connection"
sock.connect((HOST, PORT))
print "Sending json string"
sock.sendall(jsonString)
print "String sent"
finally:
sock.close()
print "Sent: {}".format(jsonString)
python 脚本执行时没有任何错误,但对接收 socat 数据的进程没有任何影响。 Python 脚本输出如下:
Attempting connection
Sending json string
Sent: {"name":"VideoStreamStatus","parameters":{"name":"video_0_0"}}
我在套接字脚本中做错了什么还是我可以在 Python 中使用不同的方法?我会很感激任何建议。谢谢。
编辑:我尝试向其发送字符串的服务器是 C++ 程序的一部分,该程序使用 boost asio 接受器来侦听特定地址和端口上的 tcp 连接。
【问题讨论】:
-
您的代码非常适合我。我的服务器
nc -l 55559在其标准输出上显示 json 字符串。请描述您正在使用的服务器,以及是什么让您认为“对接收 socat 数据的进程没有任何影响”。 -
@Robᵩ 我尝试向其发送字符串的服务器是 C++ 程序的一部分,该程序使用 boost asio 接受器侦听特定地址和端口上的 tcp 连接。
标签: python socketserver socat