Python re-using same socket and getting problems
I'm using Python to write a simple script that will connect to a host/port using a socket. I know sockets can only be used once which is why I'm not closing the socket at all but when I connect to localhost on port 80 and try a simple command like GET /
it works the first time but the second time I execute GET /
or any other HTTP command, it doesn't print the output. Here is what I have
import socket
size = 1024
host = 'localhost'
port = 80
def connectsocket(userHost, userPort):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP socket
s.connect((userHost, userPort))
while(1):
input = raw_input("Command: ")
s.send(input + '\r\n\r\n') #Send command
r = s.recv(size) #Recieve output
prin开发者_StackOverflowt(r)
connectsocket(host, port)
I'd assume this would work but here is a sample output:
amartin@homebox:~$ python socketconn.py
Command: GET /
[BUNCH OF HTML CODE]
Command: GET /
Command:
As you can see it works for the first GET /
but not for the second. How can I fix this?Given information from the comments on @samplebias' answer, I think this is similar to what you're looking to accomplish:
import errno
import socket
size = 1024
host = 'localhost'
port = 80
def connectsocket(userHost, userPort):
while(1):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP socket
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect((userHost, userPort))
command = raw_input("Command: ")
s.send(command + '\r\n\r\n') # Send command
response = s.recv(size) # Recieve output
print response
try:
s.shutdown(socket.SHUT_RDWR)
except socket.error, exc:
# Depending on the platform, shutting down one half of the
# connection can also close the opposite half
if exc.errno != errno.ENOTCONN:
raise
s.close()
connectsocket(host, port)
It probably makes sense for you to check out the Twisted library as well. You can also check out this book: Foundations of Python Network Programming.
There's also a good socket tutorial on the python documentation website that can be of assistance. Last, but not least, there's a slightly more comprehensive tutorial that I found on Google which looks great for beginners.
HTH.
You need to tell the server to keep the TCP connection open and expect more requests:
headers = 'Connection: keep-alive\r\n'
s.send(input + '\r\n' + headers + '\r\n')
Also, try specifying the HTTP version:
python socketconn.py
Command: GET / HTTP/1.1
精彩评论