'How do i add multithreading to this server side in socket programming ,i am new to socket programming I've been trying a lot to add multithreading
#import socket module
from http import server
from socket import *
import sys # In order to terminate the program
import threading
def webServer(serverport=5501):
serverSocket = socket(AF_INET, SOCK_STREAM) #Prepare a server socket
#Fill in start
serverSocket.bind(('',serverport))
serverSocket.listen(1)
print('The Web server is up on Port:',serverport)
#Fill in end
while True:
#Establish the connection
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()#Fill in start
#Fill in end
try:
message = connectionSocket.recv(1024)#Fill in start
filename=message.split()[1]
#Fill in end
f = open(filename[1:])
outputdata =f.read() #Fill in start
#Fill in end
#Send one HTTP header line into socket
#Fill in start
connectionSocket.send(bytes("HTTP/1.1 200 OK\r\n\r\n","UTF-8"))
print(outputdata)
#Fill in end
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.close()
except IOError:
#Send response message for file not found
#Fill in start
connectionSocket.send(bytes("HTTP/1.1 404 Not Found\r\n\r\n","UTF-8"))
connectionSocket.send(bytes("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n","UTF-8"))
#Fill in end
#Close client socket
#Fill in start
connectionSocket.close()
#Fill in end
serverSocket.close()
sys.exit()#Terminate the program after sending the corresponding data
if __name__ == "__main__":
try:
webServer(6789)
except KeyboardInterrupt:
sys.exit(0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
