2

我正在尝试从 CNC HAAS 控制器获取机器数据。它有一个称为 MDC 的内置软件,它充当服务器。我需要编写一个客户端程序来向 MDC 的 IP 和端口号发送请求。当我发送一个请求并接收它时,似乎服务器一次发送一个字节,所以我一次只能捕获一个字节,其他的就丢失了。如何获取全部数据。我正在使用 Python 的 socket 模块。

根据 Stack Overflow 上的上一个问题,我使用了一个 while 循环,但似乎服务器正在发送数据并关闭连接,当我的客户端程序再次循环时,其他数据丢失并且连接是关闭。

# Import socket module 
import socket  
# Create a socket object 
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)          

# Define the port on which you want to connect 
port = 5051                

# connect to the server on local computer 
s.connect(('192.168.100.3', port)) 

#sending this message will give me the status of the CNC machine


s.send(("?Q500").encode()) 



d= (s.recv(1024)).decode() 


print(d)
s.close()

预期的输出是:

>PROGRAM, MDI, IDLE, PARTS, 380

我得到的输出是>,它只是实际输出的第一个字符(字节)。

4

1 回答 1

1

更多代码会有所帮助,但我会尝试用你给我们的东西来帮助

你可以试试这个

s.send(("?Q500").encode("utf-8")) # just add an encoding

fullData = ""

while True:
    d = (s.recv(1024)).decode("utf-8")
    fullData += d

    if not d:
        print(fullData)
        s.close()
        break
于 2019-09-07T09:20:21.393 回答