This is the code I am trying to run. But the program produces a socket.error. I have a network proxy with port 8080 which connects me to the Internet, what more details do I have to add here to create this socket connection?
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.pythonlearn.com', 80))
mysock.send('GET http://www.pythonlearn.com/code/intro-short.txt HTTP/1.0\n\n')
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print data;
mysock.close()
2 Answers 2
If I run your code I get the error TypeError: a bytes-like object is required, not 'str' from line 5.
Try using: mysock.send(b'GET http://www.pythonlearn.com/code/intro-short.txt HTTP/1.0\n\n') with the b before your string indicating a bytestring.
1 Comment
socks to get through the proxy as given in this answer.I too got a type error upon running your code, and did not have an error connecting the socket. When using the socket library, make use of the makefile method so you won't have to deal with annoying details.
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_sock_input = mysock.makefile('r')
my_sock_output = mysock.makefile('w')
Now my_sock_input can use methods like readline(), without any details on bytes to reserve or wotnot. Same convenience stuff for output, but with write. Remember to close all of them!
As to your problem, I tried writing similar things using my makefile variables and I wasn't recieving any message back. So there is some other issue there.
Now, the solution. A simpler way to download a url and read its contents is using the urllib.request library. If you are on Python 2.7, just import urrlib.
import urllib.request
data = urllib.request.urlopen('http://www.pythonlearn.com/code/intro-short.txt')
readable = data.read()
print(readable)
mysock.connect(('localhost', 8080))). The proxy then will take care of connecting towww.pythonlearn.com:80