我正在使用python来传输数据,我正在尝试将读入的数据复制到文本文件中。我使用的代码工作正常,虽然我需要这个不断循环。我认为while循环应该这样做,但输出只是挂起。我哪里错了?
import socket
import sys
import time
#Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#bind the socket to the port
server_address = ('192.168.1.90', 10000)
print >> sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)
while True:
try:
#send data
message = 'Making Connection . . .'
print >> sys.stderr, '"%s"' % message
sock.sendall(message)
#look for response
amount_received = 0
amount_expected = 4096
while amount_received < amount_expected:
data = sock.recv(4096)
amount_received += len(data)
print >> sys.stderr, 'received "%s"' % data
with open ('SPI.txt', 'a') as output:
output.write(data)
time.sleep(0.5)
finally:
print >> sys.stderr, 'closing socket'
sock.close()
答案 0 :(得分:0)
sock.recv是一个阻塞调用,只有在有任何数据可供读取时才会返回。您需要使用不同的线程来回收套接字上的数据或使用非阻塞套接字。