0

So I am doing very low-level networking for school, and I wrote a program that uses HTTP to request a file from a server. I could not get the right output on my MacBook in VSCode, so I sent my exact file to a friend who ran it using the same version of Python on his Windows machine in VScode. The code worked exactly how it was supposed to on his computer, but only outputs part of the expected output on mine. Here is the program:

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()

1 Answers1

0

After trying your code, I found that it sometimes doesn't wait until the socket is done receiving before exiting the program. One way to make sure it's done is by continually receiving until s.recv(BUFFER_SIZE).decode() returns an empty string.

This can be done with a while loop, but one thing might happen is that the socket will stay open and wait for a message while the socket is open on the server. To get around this, we can use signal.alarm(seconds). This will exit the function after the specified time. Here is a modified version of receiving the html file:

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

I found the signal method from the following thread How to limit execution time of a function call in Python

Misha Melnyk
  • 409
  • 2
  • 5