Very basic Python web server - strange issue - python

I'm just starting out with Python and I'm trying to code a simple web server. Everything seems to be work except I'm having one small problem. When I request a specific file like Test.html from my web server, the data in the HTML file is repeated over and over in my client like its stuck in a loop. So instead of seeing just "Test" displayed in the web client once, I see "Test Test Test Test Test Test...many times over". This is probably a simple error but I was hoping someone could point me in the right direction.
Thanks for you help!
import socket
import sys
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket Created!!")
try:
#bind the socket
#fill in start
server_address = ('localhost', 6789)
serversocket.bind(server_address)
#fill in end
except socket.error as msg:
print("Bind failed. Error Code: " + str(msg[0]) + "Message: " +
msg[1])
sys.exit()
print("Socket bind complete")
#start listening on the socket
#fill in start
serversocket.listen(1)
#fill in end
print('Socket now listening')
while True:
#Establish the connection
connectionSocket, addr = serversocket.accept()
print('source address:' + str(addr))
try:
#Receive message from the socket
message = connectionSocket.recv(1024)
print('message = ' + str(message))
#obtian the file name carried by the HTTP request message
filename = message.split()[1]
print('filename = ' + str(filename))
f = open(filename[1:], 'rb')
outputdata = f.read()
#Send the HTTP response header line to the socket
#fill in start
connectionSocket.send(bytes('HTTP/1.1 200 OK\r\n\r\n','UTF-
8'))
#fill in end
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata)
#close the connectionSocket
#fill in start
connectionSocket.close()
#fill in end
print("Connection closed!")
except IOError:
#Send response message for file not found
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"))
#Close the client socket
#fill in start
connectionSocket.close()
serverSocket.close()

You are stuck in a loop :)
#fill in end
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata)
You're sending the contents of outputdata the number of times however long the length of the file is.
You only need connectionSocket.send(outputdata) without the for..loop to send it once.
Also, make sure you close the file you read the contents from. (f.close())

Related

No response from the sensor when connecting to the server

So i am trying to get the data from a pressure sensor Boditrak. It is connected via USB but I am not sure which port is it using... When I am connecting it I have this Data Port this is how I see it. It has its own software, but I need to get it through Python.
This is the code that I wrote:
import socket
serverAddress = 'http://localhost/api'
serverPort = 63342
bufferSize = 4096
def connect(self):
global s
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
print("Connecting to server")
s.connect((serverAddress, serverPort))
print("Connected to server\n")
response = s.recv(bufferSize)
print(response.decode("utf-8"))
Now I am not sure I am doing the right thing... but I am not sure how am I supposed to get it. Any help is appreciated.
Also the data looks like this accessed in google chrome and I get every second a new frame
When I am running the script in terminal I get nothing.
When I am reading the manual it says: "The DataPort device communicates with client devices (PC, tablet, phones) over a wifi network using a REST API. The primary role of the DataPort device is to scan one or more Boditrak sensor mats at a prescribed frequency and store those readings in a buffer"
Also do I need to have a server side and a client side? If yes, how is it supposed to look like?
Thank you!
PS. This is the live data that I want to get
Maybe I should call this GET /api/sse HTTP/1.1. But how?
For example, i took another approach but still no answer...
import socket
from urllib import parse
def connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
url = parse.urlparse('http://localhost/api')
s.connect((url[1], 80))
msg = 'GET' + 'http://localhost/api' + 'HTTP/1.1\r\n\r\n'
s.send(msg.encode('utf-8'))
response = s.recv(4096)
data = response.decode('utf-8')
print(data)
if __name__ == "__main__":
connect()
I get the following answer:
b''
UPDATE: I get some data now. Here is the code:
import socket #for sockets
import sys #for exit
def connect():
#create an INET, STREAMing socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Failed to create socket')
sys.exit()
print('Socket Created')
host = '127.0.0.1';
port = 80;
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#could not resolve
print('Hostname could not be resolved. Exiting')
sys.exit()
#Connect to remote server
s.connect((remote_ip , port))
print('Socket Connected to ' + host + ' on ip ' + remote_ip)
#Send some data to remote server
message2 = b"GET /api/sse HTTP/1.1\r\n\r\n"
try:
# Set the whole string
s.sendall(message2)
except socket.error:
# Send failed
print('Send failed')
sys.exit()
print('Message send successfully')
# Now receive data
reply2 = s.recv(16384)
print('Frames:', reply2.decode())
if __name__ == "__main__":
connect()
And the reply:
Socket Created
Socket Connected to 127.0.0.1 on ip 127.0.0.1
Message send successfully
Frames: Access-control-allow-origin: *
Access-control-allow-methods: GET, OPTIONS
Content-type: application/json
Cache-control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
Content-Length: 2583
{
"device":{ "class":"Boditrak DataPort", "name":"DataPort-******", "id":"*********", "address":"127.0.0.1", "model":"wia" },
"sensors":[ { "name":"**********", "columns":32, "rows":32, "width":470, "height":470, "minimum":0, "maximum":200, "units":"mmHg" } ],
"frames":[ { "id":719, "time":"2021-04-19 16:19:47.041", "readings":[ [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1
,1,2,1,1,2,1,1,1,0,0,0,0,1,1,0,2,2,2,2,1,1,2,3,0,0,0,1,1,2,0,1 ] ] } ],
"filters":{ "spot":false, "smooth":false, "noise":false },
"time":"2021-04-19 16:19:47.097",
"frequency":27000,
"yield":false,
"calibrated":true,
"sensorsRequired":0,
"others":[ ]
}
I have to figure it out how to get it continuously. Still sees the last frame...
Last update!
import socket #for sockets
import sys #for exit
import json
import time
t_end = time.time() + 60 * 0.2
def connect():
#create an INET, STREAMing socket
try:
global s
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Failed to create socket')
sys.exit()
print('Socket Created')
host = '127.0.0.1';
port = 80;
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#could not resolve
print('Hostname could not be resolved. Exiting')
sys.exit()
#Connect to remote server
s.connect((remote_ip , port))
print('Socket Connected to ' + host + ' on ip ' + remote_ip)
message2 = b"GET /api/sse HTTP/1.1\r\n\r\n"
try:
# Set the whole string
s.sendall(message2)
except socket.error:
# Send failed
print('Send failed')
sys.exit()
print('Message send successfully')
while time.time() < t_end:
reply2 = s.recv(4096).decode('utf-8')
response = json.dumps(reply2)
print(response)
if __name__ == "__main__":
connect()
This code is working and it is giving me data in real time. I encountered problems with an error: [WinError 10053] An established connection was aborted by the software in your host machine -- and after I deactivated my antivirus it works.
Heading
To ensure your script runs in the terminal you'll need to tell python to execute your method. To do that you can use an import guard. Add the following to the bottom of your file. This'll ensure that your connect method executes.
if __name__ == "__main__":
connect()
Given that you can access your data stream through the browser, you could make your life easier by using the requests library instead of working with sockets. It has the potential to save time by handling low level socket work for you.
For example:
import time
import requests
def connect():
url = 'http://localhost/api'
wait_time = 1
while True:
time.sleep(wait_time) # wait for 1s
r = requests.get(url) # get data
# print output to console
​print(r.text) # text based output
print(r.json()) # json output <- probably what you need given the screenshot
if __name__ == "__main__":
connect()

How can I display my HTML file in browser? I have already successfully connected the server and client

As I wrote on title, I have already successfully connected the server and client.
But the client can't display the HTML file.
I checked file path and send function. But can't find any fault.
When running the code, the code runs normally until connectionSocket.close().
But browser can't display the HTML file, just blank.
So, I checked the details and I found that connectionSocket.send(outputdata[i].encode()) send values, 1 or 3.
I don't know the reason but I'm sure that that is the cause.
Please give me your insight.
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
# Prepare a sever socket
TCPPort = 8000
BufferSize = 1024
serverSocket.bind((host, TCPPort))
serverSocket.listen(1)
while True:
# Establish the connection
print('Ready to serve...')
(connectionSocket,addr) = serverSocket.accept()
print('connectionSocket is:',connectionSocket)
try:
message = connectionSocket.recv(BufferSize)
print('message is:',message)
#filename = message.split()[1]
#print('filename is:', filename)
f = open('\HTML.html','r',encoding='UTF-8')
outputdata = f.read()
# Send one HTTP header line into socket
connectionSocket.send('HTTP/1.1 200 OK\r\n'.encode('UTF-8'))
# 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:
connectionSocket.send('HTTP/1.1 404 Not Found'.encode('UTF-8'))
connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html> ".encode('UTF-8'))
# Close client socket
connectionSocket.close()
serverSocket.close()
You need to make your server to respond by the HTTP protocol. In HTTP there are 2 newlines between headers and body and you need to send both together:
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
# Prepare a sever socket
TCPPort = 8000
BufferSize = 1024
serverSocket.bind(('127.0.0.1', TCPPort))
serverSocket.listen(1)
while True:
# Establish the connection
print('Ready to serve...')
(connectionSocket, addr) = serverSocket.accept()
print('connectionSocket is:', connectionSocket)
try:
message = connectionSocket.recv(BufferSize)
print('message is:', message)
#filename = message.split()[1]
#print('filename is:', filename)
#f = open('\HTML.html','r',encoding='UTF-8')
outputdata = "<html><body>foo</body></html>"
# Send one HTTP header line into socket
response = 'HTTP/1.1 200 OK\nConnection: close\n\n' + outputdata
connectionSocket.send(response.decode())
# Send the content of the requested file to the client
connectionSocket.close()
except IOError:
connectionSocket.send('HTTP/1.1 404 Not Found'.encode('UTF-8'))
connectionSocket.send(
"<html><head></head><body><h1>404 Not Found</h1></body></html> ".
encode('UTF-8')
)
# Close client socket
connectionSocket.close()
serverSocket.close()
Test, using: curl -X GET http://localhost:8000
Out:
<html><body>foo</body></html>

Python - Socket Communication, multiple messages

I'm stuck on this socket communication, I've looked everywhere but I haven't found an answer yet.
THE PROBLEM: I can only send 1 message from the client before it either gives me an error or ends the script.
I need to be able to send multiple messages to the server.
The server side (shown below) should be fine:
# Echo server program
import socket
import time
import os
#-----------------------------------------------------------------------------------------------------------------------
today = time.strftime('%Y.%m.%d')
logFileName = "log - " + today + ".txt"
HOST = '10.0.0.16'
PORT = 8080 # Reserve a port for your service
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket object
s.bind((HOST, PORT)) # Bind to the port
def print_write(text):
log.write(time.strftime("%H:%M:%S") + " | " + text)
log.write("\n")
print text
#-----------------------------------------------------------------------------------------------------------------------
if os.path.isfile(logFileName) is True:
log = open(logFileName, 'a+')
print_write("[SERVER] Log for " + today + " already exists.")
print_write("[SERVER] Starting comms")
else:
print "[SERVER] Log doesn't exist"
log = open(logFileName, 'a+') # Create file -> log - %date%.txt
print_write("[SERVER] Log created")
while True:
s.listen(1)
conn, addr = s.accept()
data = conn.recv(BUFFER_SIZE)
if data == "Comms Shutdown":
print_write("------ REMOTE SHUTDOWN ------")
conn.close()
raise SystemExit
else:
print_write("[COMMS] " + str(addr) + " says: " + data)
log.close()
Sorry if it's very messy and confusing but i don't have much time to finish this project, if you have any question just ask.
For the client side I don't have much but here, I'll give you this:
import socket
HOST = '10.0.0.16' # The remote host
PORT = 8080 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
msg = raw_input()
s.sendall(msg)
print msg
I know it doesn't work, it's just to give you an idea of what I need.
Thank you in advance.
The problem is, that you only read the first message from each open connection before moving on to the next. The accept() methods waits for a new connection and gives you the information needed when a new one comes in. the recv() method on the other hand, receives data from a existing connection and waits if there is none. If you want to receive multiple messages from a single client, you can just wait for the first connection and then wait for data with recv(). This could look like this:
s.listen(1)
conn, addr = s.accept()
while True:
data = conn.recv(BUFFER_SIZE)
if data == "Comms Shutdown":
print_write("------ REMOTE SHUTDOWN ------")
conn.close()
raise SystemExit
else:
print_write("[COMMS] " + str(addr) + " says: " + data)
If you want to be able to also manage multiple clients, you will have to create a thread for each one from a while loop waiting for new connections. This is a bit more complicated:
def client_handler(conn):
while True:
data = conn.recv(BUFFER_SIZE)
if data == "Comms Shutdown":
print_write("------ REMOTE SHUTDOWN ------")
conn.close()
raise SystemExit
# this will kill the server (remove the line above if you don't want that)
else:
print_write("[COMMS] " + str(addr) + " says: " + data)
while True:
s.listen(1)
conn, addr = s.accept()
recv_thread = threading.Thread(target=client_handler, args=(conn, ))
recv_thread.start()
All this code is untested. Be aware, that I omitted the logging part and the socket creation part as well as all imports.

Cache Proxy Server Returning 404 with www.google.com

I have a homework assignment which involves implementing a proxy cache server in Python for web pages. Here is my implementation of it
from socket import *
import sys
def main():
#Create a server socket, bind it to a port and start listening
tcpSerSock = socket(AF_INET, SOCK_STREAM) #Initializing socket
tcpSerSock.bind(("", 8030)) #Binding socket to port
tcpSerSock.listen(5) #Listening for page requests
while True:
#Start receiving data from the client
print 'Ready to serve...'
tcpCliSock, addr = tcpSerSock.accept()
print 'Received a connection from:', addr
message = tcpCliSock.recv(1024)
print message
#Extract the filename from the given message
filename = ""
try:
filename = message.split()[1].partition("/")[2].replace("/", "")
except:
continue
fileExist = False
try: #Check whether the file exists in the cache
f = open(filename, "r")
outputdata = f.readlines()
fileExist = True
#ProxyServer finds a cache hit and generates a response message
tcpCliSock.send("HTTP/1.0 200 OK\r\n")
tcpCliSock.send("Content-Type:text/html\r\n")
for data in outputdata:
tcpCliSock.send(data)
print 'Read from cache'
except IOError: #Error handling for file not found in cache
if fileExist == False:
c = socket(AF_INET, SOCK_STREAM) #Create a socket on the proxyserver
try:
srv = getaddrinfo(filename, 80)
c.connect((filename, 80)) #https://docs.python.org/2/library/socket.html
# Create a temporary file on this socket and ask port 80 for
# the file requested by the client
fileobj = c.makefile('r', 0)
fileobj.write("GET " + "http://" + filename + " HTTP/1.0\r\n")
# Read the response into buffer
buffr = fileobj.readlines()
# Create a new file in the cache for the requested file.
# Also send the response in the buffer to client socket and the
# corresponding file in the cache
tmpFile = open(filename,"wb")
for data in buffr:
tmpFile.write(data)
tcpCliSock.send(data)
except:
print "Illegal request"
else: #File not found
print "404: File Not Found"
tcpCliSock.close() #Close the client and the server sockets
main()
I configured my browsers to use my proxy server like so
But my problem when I run it is that no matter what web page I try to access it returns a 404 error with the initial connection and then a connection reset error with subsequent connections. I have no idea why so any help would be greatly appreciated, thanks!
There are quite a number of issues with your code.
Your URL parser is quite cumbersome. Instead of the line
filename = message.split()[1].partition("/")[2].replace("/", "")
I would use
import re
parsed_url = re.match(r'GET\s+http://(([^/]+)(.*))\sHTTP/1.*$', message)
local_path = parsed_url.group(3)
host_name = parsed_url.group(2)
filename = parsed_url.group(1)
If you catch an exception there, you should probably throw an error because it is a request your proxy doesn't understand (e.g. a POST).
When you assemble your request to the destination server, you then use
fileobj.write("GET {object} HTTP/1.0\n".format(object=local_path))
fileobj.write("Host: {host}\n\n".format(host=host_name))
You should also include some of the header lines from the original request because they can make a major difference to the returned content.
Furthermore, you currently cache the entire response with all header lines, so you should not add your own when serving from cache.
What you have doesn't work, anyway, because there is no guarantee that you will get a 200 and text/html content. You should check the response code and only cache if you did indeed get a 200.

Python not sending all data, only 4kb

I am attempting to create a Python web server however it seems to not be able to send any files larger then 4KB. If the file is above 4KB in size it just cuts off the end of the text/image past 4KB. Anything embedded from other sources (Amazon S3/Twitter) work fine.
Here is the server code. It is a bit of a mess at the moment but I am focused on getting it to work. Afterwards I will add more security to the code.
'''
Simple socket server using threads
'''
import socket
import sys
import time
import os
from thread import *
HOST = '' # Symbolic name meaning all available interfaces
PORT = 80 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(4096)
print data
dataSplit = data.split(' ')
print dataSplit
contentType = "text/html"
if(dataSplit[1].endswith(".html")):
print "HTML FILE DETECTED"
contentType = "text/html"
elif(dataSplit[1].endswith(".png")):
print "PNG FILE DETECTED"
contentType = "image/png"
elif(dataSplit[1].endswith(".css")):
print "CSS FILE DETECTED"
contentType = "text/css"
else:
print "NO MIMETYPE DEFINED"
conn.sendall('HTTP/1.1 200 OK\nServer: TestWebServ/0.0.1\nContent-Length: ' + str(os.path.getsize('index.html')) + '\nConnection: close\nContent-Type:' + contentType + '\n\n')
print '\n\n\n\n\n\n\n\n'
with open(dataSplit[1][1:]) as f:
fileText = f.read()
n = 1000
fileSplitToSend = [fileText[i:i+n] for i in range(0, len(fileText), n)]
for lineToSend in fileSplitToSend:
conn.sendall(lineToSend)
break
if not data:
break
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close
Thank you for your time.
So, thanks you the user "YOU" we found the problem. I had this code:
conn.sendall('HTTP/1.1 200 OK\nServer: TestWebServ/0.0.1\nContent-Length: ' + str(os.path.getsize('index.html')) + '\nConnection: close\nContent-Type:' + contentType + '\n\n')
instead of this code:
conn.sendall('HTTP/1.1 200 OK\nServer: TestWebServ/0.0.1\nContent-Length: ' + str(os.path.getsize(dataSplit[1][1:])) + '\nConnection: close\nContent-Type:' + contentType + '\n\n')
The problem was that I was sending the file size for index.html for every file, so Chrome and other browsers just removed the extra data. It just so happened index.html was 4KB so I though it was a packet limitation or something in that area.

Categories

Resources