.recv function Socket programming TCP Server in Python
<p>Im having trouble getting my very basic and simple TCP Server to properly work with http requests. This is what I have so far</p>

<pre><code>from socket import *
import sys 
serverSocket = socket(AF_INET, SOCK_STREAM)


serverSocket.bind(('', 4567))
serverSocket.listen(1)

while True:
    print('Ready to serve...')
    connectionSocket, addr =  serverSocket.accept()
    print("connected from: ", addr)
    try:
        message = connectionSocket.recv(1024)
        filename = message.split()[1]                 
        f = open(filename[1:])         
        outputdata = f.read()
        connectionSocket.send("HTTP/1.1 200 OK\r\n") 
        for i in range(0, len(outputdata)):           
            connectionSocket.send(outputdata[i].encode())
            connectionSocket.send("\r\n".encode())
        connectionSocket.close()
    except IOError:
        connectionSocket.send("file not found")
        serverSocket.close()
sys.exit()
</code></pre>

<p>The error comes from the open statement. I dont fully understand how this line of code's return value is organized.</p>

<pre><code>message = connectionSocket.recv(1024)
</code></pre>

<p>I know that the return value is in bytes but when I try to use a fuction to turn it into a string like decode() i get errors as well</p>

<p>I have the .py file and the html file sitting in the same directory on my local machine and the way I test this is I just run this and open up a browser and type in</p>

<pre><code>http://127.0.0.1:4567/helloworld.html
</code></pre>

<p>My code then promptly crashes after receiving the HTTP request.
Any and all help will be greatly appreciated!</p>

<p>There are numerous problems with your code and since you don't state what specific issues you are concerned about, here is what I see:</p>

<pre><code>        connectionSocket.send(outputdata[i].encode())
        connectionSocket.send("\r\n".encode())
</code></pre>

<p>That appears to send a newline after every character you send back to the client.</p>

<p>Also, it doesn't deal with the client disconnecting because you're sending back invalid data.</p>

<p>Even if what you were trying to do didn't have these errors in it, you don't appear to be attempting to send back a valid http response.   </p>

<p><a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html" rel="nofollow">https://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html</a></p>

python sockets http tcp decode