因此,我正在为学校进行非常底层的网络连接,并且编写了一个使用HTTP从服务器请求文件的程序。我无法在VSCode的MacBook上获得正确的输出,因此我将确切的文件发送给了一个朋友,该朋友在VScode的Windows计算机上使用相同版本的Python运行了该文件。该代码完全按照他的计算机上的预期工作,但仅输出我的预期输出的一部分。这是程序:
import socket
# Variables
serverIP = 'gaia.cs.umass.edu'
serverPort = 80
BUFFER_SIZE = 262144
messageSent = 'GET /kurose_ross/interactive/index.php HTTP/1.1\r\nHost:gaia.cs.umass.edu\r\n\r\n'
# Attempt to create socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket successfully created")
except socket.error as error:
print ("socket creation failed with error %s") %(error)
# Connect
s.connect((serverIP, serverPort))
# Send Message
s.send(messageSent.encode())
# Receive Message
messageReceived = s.recv(BUFFER_SIZE).decode()
print(messageReceived)
s.close()
答案 0 :(得分:0)
尝试您的代码后,我发现有时它不等到套接字完成接收后再退出程序。确保完成的一种方法是持续接收,直到s.recv(BUFFER_SIZE).decode()
返回空字符串为止。
这可以通过while循环来完成,但是可能发生的事情是套接字将保持打开状态,并在服务器上打开套接字时等待消息。为了解决这个问题,我们可以使用signal.alarm(seconds)
。在指定的时间后将退出功能。这是接收html文件的修改版本:
import signal
def signal_handler(signum, frame): #function to call for signal
raise Exception("Alarm Done")
signal.signal(signal.SIGALRM, signal_handler) #sets signal_handler to be called when alarm ends
signal.alarm(1) #The alarm will raise an exception after 1 second
finalMsg = ""
messageReceived = s.recv(BUFFER_SIZE).decode()
while messageReceived != "":
finalMsg += messageReceived
try: #By putting it in a try/except, the exception will break out of the function
messageReceived = s.recv(BUFFER_SIZE).decode()
except Exception as e:
messageReceived = ""
signal.alarm(0) #Resets alarm
messageReceived = finalMsg
我从以下线程中找到了信号方法 How to limit execution time of a function call in Python