Files not displaying in browser using a multi-threaded python server socket Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How do I copy a file in Python?How to use threading in Python?Multiprocessing vs Threading Pythongot problems about a simple server written by pythonFind all files in a directory with extension .txt in PythonHow do you append to a file in Python?Pythonic way to create a long multi-line stringTCP connection - server only sends message after closing socketHow can I achieve multi-threading in Python? [socket programming]Multithread Socket in Python, Message Error UniUnicodeDecodeError

Why is an operator the quantum mechanical analogue of an observable?

Married in secret, can marital status in passport be changed at a later date?

How to get even lighting when using flash for group photos near wall?

Map material from china not allowed to leave the country

Putting Ant-Man on house arrest

Co-worker works way more than he should

What is this word supposed to be?

Visa-free travel to the US using refugee travel document from Spain?

I preordered a game on my Xbox while on the home screen of my friend's account. Which of us owns the game?

What was Apollo 13's "Little Jolt" after MECO?

What's the difference between using dependency injection with a container and using a service locator?

What is the least dense liquid under normal conditions?

Raising a bilingual kid. When should we introduce the majority language?

Are all CP/M-80 implementations binary compatible?

What's parked in Mil Moscow helicopter plant?

Is accepting an invalid credit card number a security issue?

Could Neutrino technically as side-effect, incentivize centralization of the bitcoin network?

"My boss was furious with me and I have been fired" vs. "My boss was furious with me and I was fired"

What is the best way to deal with NPC-NPC combat?

What is a 'Key' in computer science?

Is it acceptable to use working hours to read general interest books?

How long after the last departure shall the airport stay open for an emergency return?

What is it called when you ride around on your front wheel?

The art of proof summarizing. Are there known rules, or is it a purely common sense matter?



Files not displaying in browser using a multi-threaded python server socket



Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How do I copy a file in Python?How to use threading in Python?Multiprocessing vs Threading Pythongot problems about a simple server written by pythonFind all files in a directory with extension .txt in PythonHow do you append to a file in Python?Pythonic way to create a long multi-line stringTCP connection - server only sends message after closing socketHow can I achieve multi-threading in Python? [socket programming]Multithread Socket in Python, Message Error UniUnicodeDecodeError



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















The problem I'm running into is as follows:



I've built a multi-threaded TCP server using the socket module in Python (or at least, I've tried to). The server worked just fine in its single-threaded implementation, and seems to send the file just fine through the CLI when I'm using it with a client script that I've written, but when I use it with a browser, the files simply don't show up - the HTTP status message will come through (HTTP/1.0 200 OK or HTTP/1.0 404 File Not Found), but the file itself will not... or if it does, it doesn't show up in the browser.



If someone could take a look at my code and help me figure out what's going on, I would be very appreciative. Here is the main part of my code (I've omitted the import statements and the if dunder-name equals dunder-main part of the code...):



#Thread function:

def threaded(connectionSocket):

while True:

try:
#Request received from client
message = connectionSocket.recv(1024)

#Create received time stamp
recv_time = time.time()

#If the request is coming from the CLI, do this:
filename = message

#If the request is coming from a browser, do this:
if len(message.decode('utf-8')) > 20:
#Parse message from client
filename = message.split()[1]

filename = filename.decode('utf-8')
f = open('.' + filename, 'r')
outputdata = f.read(1024)

#Send HTTP 200 OK Response message
connectionSocket.sendall(bytes("HTTP/1.0 200 OKn", "utf-8"))

#Send data to client
connectionSocket.sendall(outputdata.encode('utf-8'))

#Display response to console
print("HTTP/1.0 200 OK")

#Create sent time stamp
sent_time = time.time()
break

except:

#Send response message for file not found
connectionSocket.send(bytes('HTTP/1.0 404 File Not Found n', 'utf-8'))

#Display to console
print("HTTP/1.0 404 File Not Found")

#Create time stamp
sent_time = time.time()
break

#Calculate RTT
rtt = round((sent_time - recv_time), 3)

#Display RTT
print("RTT: " + str(rtt) + "ms")

#Close connection and release lock
connectionSocket.close()
data_lock.release()
print("Lock Releasedn")

#The serve function which generates the server socket and initiates the thread

def serve():
#Create a server socket
serverSocket = socket(AF_INET, SOCK_STREAM)

#Prepare a server socket
HOST = '127.0.0.1'
PORT = 50007
serverSocket.bind((HOST, PORT))
serverSocket.listen(5)

while True:

#Acquire lock
data_lock.acquire()
print("Lock acquired")
print('Ready to serve...')

#Establish the connection
connectionSocket, addr = serverSocket.accept()
print('Connected by ' + str(addr))

#Start new thread
start_new_thread(threaded, (connectionSocket,))
break

#Close this socket
serverSocket.close()

#The main function:
def Main():
while True:
serve()


I feel like I'm probably missing something rather obvious, but I'm rather new to socket programming and multi-threading and all such as that. Any advice would be very helpful.



Thank you!










share|improve this question






















  • Can you fill in the missing bits of your code (such as start_new_thread) so that it can run without modifications? There are many problems with your code, and you shouldn’t be writing an HTTP server this way, but if this is an exercise, then it may be possible to pinpoint which of the problems is causing the behavior you describe.

    – Vasiliy Faronov
    Mar 22 at 17:11











  • I'm surprised that this worked in the single threaded version. This is not a valid HTTP response you send there, i.e. there is no delimiter between HTTP header and body, the line end is n instead of rn, no length is given but the socket does not get closed ... If I would be a browser I would refuse to deal with such garbage data.

    – Steffen Ullrich
    Mar 22 at 18:47












  • @SteffenUllrich! That was precisely what I was missing! It had originally had rn in the single-threaded version, but I suppose it got lost in the transition. It's an obvious thing I was overlooking, but thanks to your eagle eye, I've fixed it and it works just fine! Fine enough for me, anyway. Thankfully this is just an academic exercise, and thank you all for your help. It is much appreciated.

    – Carter Jones
    Mar 25 at 14:18


















0















The problem I'm running into is as follows:



I've built a multi-threaded TCP server using the socket module in Python (or at least, I've tried to). The server worked just fine in its single-threaded implementation, and seems to send the file just fine through the CLI when I'm using it with a client script that I've written, but when I use it with a browser, the files simply don't show up - the HTTP status message will come through (HTTP/1.0 200 OK or HTTP/1.0 404 File Not Found), but the file itself will not... or if it does, it doesn't show up in the browser.



If someone could take a look at my code and help me figure out what's going on, I would be very appreciative. Here is the main part of my code (I've omitted the import statements and the if dunder-name equals dunder-main part of the code...):



#Thread function:

def threaded(connectionSocket):

while True:

try:
#Request received from client
message = connectionSocket.recv(1024)

#Create received time stamp
recv_time = time.time()

#If the request is coming from the CLI, do this:
filename = message

#If the request is coming from a browser, do this:
if len(message.decode('utf-8')) > 20:
#Parse message from client
filename = message.split()[1]

filename = filename.decode('utf-8')
f = open('.' + filename, 'r')
outputdata = f.read(1024)

#Send HTTP 200 OK Response message
connectionSocket.sendall(bytes("HTTP/1.0 200 OKn", "utf-8"))

#Send data to client
connectionSocket.sendall(outputdata.encode('utf-8'))

#Display response to console
print("HTTP/1.0 200 OK")

#Create sent time stamp
sent_time = time.time()
break

except:

#Send response message for file not found
connectionSocket.send(bytes('HTTP/1.0 404 File Not Found n', 'utf-8'))

#Display to console
print("HTTP/1.0 404 File Not Found")

#Create time stamp
sent_time = time.time()
break

#Calculate RTT
rtt = round((sent_time - recv_time), 3)

#Display RTT
print("RTT: " + str(rtt) + "ms")

#Close connection and release lock
connectionSocket.close()
data_lock.release()
print("Lock Releasedn")

#The serve function which generates the server socket and initiates the thread

def serve():
#Create a server socket
serverSocket = socket(AF_INET, SOCK_STREAM)

#Prepare a server socket
HOST = '127.0.0.1'
PORT = 50007
serverSocket.bind((HOST, PORT))
serverSocket.listen(5)

while True:

#Acquire lock
data_lock.acquire()
print("Lock acquired")
print('Ready to serve...')

#Establish the connection
connectionSocket, addr = serverSocket.accept()
print('Connected by ' + str(addr))

#Start new thread
start_new_thread(threaded, (connectionSocket,))
break

#Close this socket
serverSocket.close()

#The main function:
def Main():
while True:
serve()


I feel like I'm probably missing something rather obvious, but I'm rather new to socket programming and multi-threading and all such as that. Any advice would be very helpful.



Thank you!










share|improve this question






















  • Can you fill in the missing bits of your code (such as start_new_thread) so that it can run without modifications? There are many problems with your code, and you shouldn’t be writing an HTTP server this way, but if this is an exercise, then it may be possible to pinpoint which of the problems is causing the behavior you describe.

    – Vasiliy Faronov
    Mar 22 at 17:11











  • I'm surprised that this worked in the single threaded version. This is not a valid HTTP response you send there, i.e. there is no delimiter between HTTP header and body, the line end is n instead of rn, no length is given but the socket does not get closed ... If I would be a browser I would refuse to deal with such garbage data.

    – Steffen Ullrich
    Mar 22 at 18:47












  • @SteffenUllrich! That was precisely what I was missing! It had originally had rn in the single-threaded version, but I suppose it got lost in the transition. It's an obvious thing I was overlooking, but thanks to your eagle eye, I've fixed it and it works just fine! Fine enough for me, anyway. Thankfully this is just an academic exercise, and thank you all for your help. It is much appreciated.

    – Carter Jones
    Mar 25 at 14:18














0












0








0








The problem I'm running into is as follows:



I've built a multi-threaded TCP server using the socket module in Python (or at least, I've tried to). The server worked just fine in its single-threaded implementation, and seems to send the file just fine through the CLI when I'm using it with a client script that I've written, but when I use it with a browser, the files simply don't show up - the HTTP status message will come through (HTTP/1.0 200 OK or HTTP/1.0 404 File Not Found), but the file itself will not... or if it does, it doesn't show up in the browser.



If someone could take a look at my code and help me figure out what's going on, I would be very appreciative. Here is the main part of my code (I've omitted the import statements and the if dunder-name equals dunder-main part of the code...):



#Thread function:

def threaded(connectionSocket):

while True:

try:
#Request received from client
message = connectionSocket.recv(1024)

#Create received time stamp
recv_time = time.time()

#If the request is coming from the CLI, do this:
filename = message

#If the request is coming from a browser, do this:
if len(message.decode('utf-8')) > 20:
#Parse message from client
filename = message.split()[1]

filename = filename.decode('utf-8')
f = open('.' + filename, 'r')
outputdata = f.read(1024)

#Send HTTP 200 OK Response message
connectionSocket.sendall(bytes("HTTP/1.0 200 OKn", "utf-8"))

#Send data to client
connectionSocket.sendall(outputdata.encode('utf-8'))

#Display response to console
print("HTTP/1.0 200 OK")

#Create sent time stamp
sent_time = time.time()
break

except:

#Send response message for file not found
connectionSocket.send(bytes('HTTP/1.0 404 File Not Found n', 'utf-8'))

#Display to console
print("HTTP/1.0 404 File Not Found")

#Create time stamp
sent_time = time.time()
break

#Calculate RTT
rtt = round((sent_time - recv_time), 3)

#Display RTT
print("RTT: " + str(rtt) + "ms")

#Close connection and release lock
connectionSocket.close()
data_lock.release()
print("Lock Releasedn")

#The serve function which generates the server socket and initiates the thread

def serve():
#Create a server socket
serverSocket = socket(AF_INET, SOCK_STREAM)

#Prepare a server socket
HOST = '127.0.0.1'
PORT = 50007
serverSocket.bind((HOST, PORT))
serverSocket.listen(5)

while True:

#Acquire lock
data_lock.acquire()
print("Lock acquired")
print('Ready to serve...')

#Establish the connection
connectionSocket, addr = serverSocket.accept()
print('Connected by ' + str(addr))

#Start new thread
start_new_thread(threaded, (connectionSocket,))
break

#Close this socket
serverSocket.close()

#The main function:
def Main():
while True:
serve()


I feel like I'm probably missing something rather obvious, but I'm rather new to socket programming and multi-threading and all such as that. Any advice would be very helpful.



Thank you!










share|improve this question














The problem I'm running into is as follows:



I've built a multi-threaded TCP server using the socket module in Python (or at least, I've tried to). The server worked just fine in its single-threaded implementation, and seems to send the file just fine through the CLI when I'm using it with a client script that I've written, but when I use it with a browser, the files simply don't show up - the HTTP status message will come through (HTTP/1.0 200 OK or HTTP/1.0 404 File Not Found), but the file itself will not... or if it does, it doesn't show up in the browser.



If someone could take a look at my code and help me figure out what's going on, I would be very appreciative. Here is the main part of my code (I've omitted the import statements and the if dunder-name equals dunder-main part of the code...):



#Thread function:

def threaded(connectionSocket):

while True:

try:
#Request received from client
message = connectionSocket.recv(1024)

#Create received time stamp
recv_time = time.time()

#If the request is coming from the CLI, do this:
filename = message

#If the request is coming from a browser, do this:
if len(message.decode('utf-8')) > 20:
#Parse message from client
filename = message.split()[1]

filename = filename.decode('utf-8')
f = open('.' + filename, 'r')
outputdata = f.read(1024)

#Send HTTP 200 OK Response message
connectionSocket.sendall(bytes("HTTP/1.0 200 OKn", "utf-8"))

#Send data to client
connectionSocket.sendall(outputdata.encode('utf-8'))

#Display response to console
print("HTTP/1.0 200 OK")

#Create sent time stamp
sent_time = time.time()
break

except:

#Send response message for file not found
connectionSocket.send(bytes('HTTP/1.0 404 File Not Found n', 'utf-8'))

#Display to console
print("HTTP/1.0 404 File Not Found")

#Create time stamp
sent_time = time.time()
break

#Calculate RTT
rtt = round((sent_time - recv_time), 3)

#Display RTT
print("RTT: " + str(rtt) + "ms")

#Close connection and release lock
connectionSocket.close()
data_lock.release()
print("Lock Releasedn")

#The serve function which generates the server socket and initiates the thread

def serve():
#Create a server socket
serverSocket = socket(AF_INET, SOCK_STREAM)

#Prepare a server socket
HOST = '127.0.0.1'
PORT = 50007
serverSocket.bind((HOST, PORT))
serverSocket.listen(5)

while True:

#Acquire lock
data_lock.acquire()
print("Lock acquired")
print('Ready to serve...')

#Establish the connection
connectionSocket, addr = serverSocket.accept()
print('Connected by ' + str(addr))

#Start new thread
start_new_thread(threaded, (connectionSocket,))
break

#Close this socket
serverSocket.close()

#The main function:
def Main():
while True:
serve()


I feel like I'm probably missing something rather obvious, but I'm rather new to socket programming and multi-threading and all such as that. Any advice would be very helpful.



Thank you!







python multithreading sockets






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 22 at 15:54









Carter JonesCarter Jones

1




1












  • Can you fill in the missing bits of your code (such as start_new_thread) so that it can run without modifications? There are many problems with your code, and you shouldn’t be writing an HTTP server this way, but if this is an exercise, then it may be possible to pinpoint which of the problems is causing the behavior you describe.

    – Vasiliy Faronov
    Mar 22 at 17:11











  • I'm surprised that this worked in the single threaded version. This is not a valid HTTP response you send there, i.e. there is no delimiter between HTTP header and body, the line end is n instead of rn, no length is given but the socket does not get closed ... If I would be a browser I would refuse to deal with such garbage data.

    – Steffen Ullrich
    Mar 22 at 18:47












  • @SteffenUllrich! That was precisely what I was missing! It had originally had rn in the single-threaded version, but I suppose it got lost in the transition. It's an obvious thing I was overlooking, but thanks to your eagle eye, I've fixed it and it works just fine! Fine enough for me, anyway. Thankfully this is just an academic exercise, and thank you all for your help. It is much appreciated.

    – Carter Jones
    Mar 25 at 14:18


















  • Can you fill in the missing bits of your code (such as start_new_thread) so that it can run without modifications? There are many problems with your code, and you shouldn’t be writing an HTTP server this way, but if this is an exercise, then it may be possible to pinpoint which of the problems is causing the behavior you describe.

    – Vasiliy Faronov
    Mar 22 at 17:11











  • I'm surprised that this worked in the single threaded version. This is not a valid HTTP response you send there, i.e. there is no delimiter between HTTP header and body, the line end is n instead of rn, no length is given but the socket does not get closed ... If I would be a browser I would refuse to deal with such garbage data.

    – Steffen Ullrich
    Mar 22 at 18:47












  • @SteffenUllrich! That was precisely what I was missing! It had originally had rn in the single-threaded version, but I suppose it got lost in the transition. It's an obvious thing I was overlooking, but thanks to your eagle eye, I've fixed it and it works just fine! Fine enough for me, anyway. Thankfully this is just an academic exercise, and thank you all for your help. It is much appreciated.

    – Carter Jones
    Mar 25 at 14:18

















Can you fill in the missing bits of your code (such as start_new_thread) so that it can run without modifications? There are many problems with your code, and you shouldn’t be writing an HTTP server this way, but if this is an exercise, then it may be possible to pinpoint which of the problems is causing the behavior you describe.

– Vasiliy Faronov
Mar 22 at 17:11





Can you fill in the missing bits of your code (such as start_new_thread) so that it can run without modifications? There are many problems with your code, and you shouldn’t be writing an HTTP server this way, but if this is an exercise, then it may be possible to pinpoint which of the problems is causing the behavior you describe.

– Vasiliy Faronov
Mar 22 at 17:11













I'm surprised that this worked in the single threaded version. This is not a valid HTTP response you send there, i.e. there is no delimiter between HTTP header and body, the line end is n instead of rn, no length is given but the socket does not get closed ... If I would be a browser I would refuse to deal with such garbage data.

– Steffen Ullrich
Mar 22 at 18:47






I'm surprised that this worked in the single threaded version. This is not a valid HTTP response you send there, i.e. there is no delimiter between HTTP header and body, the line end is n instead of rn, no length is given but the socket does not get closed ... If I would be a browser I would refuse to deal with such garbage data.

– Steffen Ullrich
Mar 22 at 18:47














@SteffenUllrich! That was precisely what I was missing! It had originally had rn in the single-threaded version, but I suppose it got lost in the transition. It's an obvious thing I was overlooking, but thanks to your eagle eye, I've fixed it and it works just fine! Fine enough for me, anyway. Thankfully this is just an academic exercise, and thank you all for your help. It is much appreciated.

– Carter Jones
Mar 25 at 14:18






@SteffenUllrich! That was precisely what I was missing! It had originally had rn in the single-threaded version, but I suppose it got lost in the transition. It's an obvious thing I was overlooking, but thanks to your eagle eye, I've fixed it and it works just fine! Fine enough for me, anyway. Thankfully this is just an academic exercise, and thank you all for your help. It is much appreciated.

– Carter Jones
Mar 25 at 14:18













0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55303438%2ffiles-not-displaying-in-browser-using-a-multi-threaded-python-server-socket%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55303438%2ffiles-not-displaying-in-browser-using-a-multi-threaded-python-server-socket%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript