Hello guys..!!
I'm new to python and I have a task which require me to write a simple TCP server which will interact with the web browser. I have done some coding as well as researching over the internet to find relevant notes and materials but none helped.
What I want to do is that I would run a TCP server which will open a socket and listen on some particula port e.g. 12000. Then configure the browser to connect on that port number and try to send a GET request. For example if I type http://localhost:12000/www.google.com the server should be able to return the page and display it on the browser. This is what looks like doing the job but not complete...
# import the required library
import socket, threading
class ClientThread(threading.Thread):
def __init__(self,ip,port, socket):
threading.Thread.__init__(self)
self.ip = ip
self.port = port
self.socket = socket
print "[+] New thread started for "+ip+":"+str(port)
# Entry point for thread
def run(self):
print "Connection from : "+ip+":"+str(port)
#clientsock.send("\nWelcome to the server\n\n")
self.socket.send("\nWelcome to the server\n\n")
data = "dummydata"
while len(data):
data = self.socket.recv(2048) #clientsock.recv(2048)
print "Client sent : "+data
self.socket.sendall("You sent me : " +data)
print "Client disconnected..."
host = "localhost"
port = 9999
# Create server socket object
tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Port reused immediately after the socket is closed
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind the server socket to the port
tcpsock.bind((host,port))
threads = []
while True:
# Start listening to new connections
tcpsock.listen(4)
print "\nListening for incoming connections..."
(clientsock, (ip, port)) = tcpsock.accept()
# Create new thread
newthread = ClientThread(ip, port, clientsock)
# Start new thread
newthread.start()
threads.append(newthread)
# Wait for threads to terminate
for t in threads:
t.join()
What this code returns is only what the broswer send. I want to know how the server could return the whole html documents (jpge files and anything) so it can be displayed on the broswer. I asking if anyone can point me to the right direction or give some hints that would help.
Thanks.