简体   繁体   English

使用 Python 将 TCP 数据流式传输到客户端

[英]Streaming TCP data to a Client with Python

I have read several different SO posts on using python as a TCP client and am not able to connect to a server sending data via TCP at 1hz which is hosted locally.我已经阅读了几个关于使用 python 作为 TCP 客户端的不同 SO 帖子,但无法连接到通过本地托管的 1hz 的 TCP 发送数据的服务器。 The connection parameters I am using are:我使用的连接参数是:

import socket
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ip=socket.gethostbyname("127.0.0.1")
port=1234
address=(ip,port)
client.connect(address)
while True:
    print("test1")
    data = client.recv(1024)
    print("test2")
    print(data)

I believe that it is failing on the second line of the while statement but do not know why because it hangs and I am not given an error.我相信它在 while 语句的第二行失败,但不知道为什么,因为它挂起并且我没有收到错误消息。 Below are links to the SO articles, I have read and I have attached a screenshot from a TCP client tool that I am able to connect to the data server with.以下是 SO 文章的链接,我已阅读并附上了来自 TCP 客户端工具的屏幕截图,我可以使用该工具连接到数据服务器。 I'm expecting the data to stream in my print statement, is this not how it works?我期待数据在我的打印语句中流动,这不是它的工作原理吗? Whats the best way to make a persistent connection to a TCP connection with python?使用 python 与 TCP 连接建立持久连接的最佳方法是什么?

Researched: (Very) basic Python client socket example , Python continuous TCP connection , Python stream data over TCP研究:( 非常)基本的Python客户端套接字示例Python连续TCP连接TCP上的Python流数据

在此处输入图片说明

Working with sockets: In order to communicate over a socket, you have to open a connection to an existing socket (a "client"), or create an open socket that waits for a connection (a "server").使用套接字:为了通过套接字进行通信,您必须打开到现有套接字的连接(“客户端”),或者创建一个等待连接的打开套接字(“服务器”)。 In your code, you haven't done either, so recv() is waiting for data that will never arrive.在您的代码中,您也没有这样做,因此recv()正在等待永远不会到达的数据。

The simple case is connecting as a client to a server which is waiting/listening for connections.简单的情况是作为客户端连接到正在等待/侦听连接的服务器。 In your case, assuming that there is a server on your machine listening on port 1234, you simply need to add a connect() call.在您的情况下,假设您的机器上有一台服务器侦听端口 1234,您只需添加一个connect()调用。

import socket
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ip=socket.gethostbyname("127.0.0.1")
port=1234
address=(ip,port)
client.connect(address)  ## <--Add this line.
while True:
    print("test1")
    data = client.recv(1024)
    print("test2")
    print(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM