Skip to content

Instantly share code, notes, and snippets.

@bee-san
Last active October 24, 2016 15:09
Show Gist options
  • Select an option

  • Save bee-san/0e5225322efc9ef16a4327a3916f2339 to your computer and use it in GitHub Desktop.

Select an option

Save bee-san/0e5225322efc9ef16a4327a3916f2339 to your computer and use it in GitHub Desktop.
from socket import *
serverPort = 12008 # large port number as not to interfer, still lower than 2^16-1
serverName = 'hostname'
serverSocket = socket(AF_INET, SOCK_STREAM)
# Makes it so it uses IPV4 and TCP
serverSocket.bind(('', serverPort))
# binds socket to server
serverSocket.listen(1)
# Only queue up one connection
while True:
# Establish the connection
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
# When client connects, create a client socket
try:
message = connectionSocket.recv(1024)
# receive 1024 bits (or bytes) of message from client
filename = message.split()[1]
# parse HTML GET request so it only shows file name. Splits by whitespace and only first list argument
f = open(filename[1:])
# opens requested file
outputdata = f.read()
# Gets file data
f.close()
# closes file
connectionSocket.send('HTTP/1.1 200 OK\r\n\r\n')
# Sends HTTP OK response
# Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
# closes socket
except IOError:
# if file doesnt exist, send 404 response message
print('ioError')
connectionSocket.send("Error: 404. File not found.")
connectionSocket.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment