Click here to Skip to main content
15,889,706 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#Get socket function
import socket
import sys 

# All connections and bindings OK. Start is called
def start():
	while True:
    # Constantly listens for html messages from the client. All protocols and connections must be successful
		print('Accepting connection from {}'.format(SERVER))
		connection, address = serverSocket.accept()

	try:
		# Message is taken from client then decoded. The max byte size of the message is 5000 from the ts.html file
		msg = connection.recv(5000).decode()
		
		# The path is extraced from the requested object in the message
		# The path is located at the end of the HTTP header (aka [1])
		filename = msg.split()[1]
		# The path is read starting from the second character to accommodate for the '\' at the beginning of the HTTP request
		f = open(filename[1:])
		
		#This sends one HTTP header line to the server socket
		data = f.read()
		
		#This sends the HTTP 200 OK header line to the server
		connection.send("HTTP/1.1 200 OK\r\n\r\n".encode()) 
 
		#The client recieves the requested content of the file
		for i in range(0, (len(data)+1)):  
			connection.send(data[i].encode())
		connection.send("\r\n".encode()) 
		
		# If the message has successfully ended, this will close the connection.
		connection.close()

	except IOError:
			#If the file is not found, this message will print to the client
			connection.send("HTTP/1.1 404 Not Found\r\n\r\n".encode())
			connection.send("<html><head></head><body><h1>404 File Not Found</h1></body></html>\r\n".encode())

			#Closes client socket
			connection.close()


#Create a TCP/IP socket for server 
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#The port that is used is defined here
serverPort = 1993

#Binds the port to the address
serverSocket.bind(("", serverPort))
#The user will see the host name on their screen
SERVER= socket.gethostname()
#Listen for incoming connections
serverSocket.listen(5)

#Start function is called once all connections and protocols are established
start()

#Closes the server socket
serverSocket.close()  

#Exit or terminate the program *


What I have tried:

I'm creating a server then launching two html webpages. Keep running into error at terminal:
"[Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted" after closing and reopening Python socket
Posted
Updated 5-Mar-21 16:02pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900