Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3.3 HTML Client TypeError: 'str' does not support the buffer interface

import socket

# Set up a TCP/IP socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

# Connect as client to a selected server
# on a specified port
s.connect(("www.wellho.net",80))

# Protocol exchange - sends and receives
s.send("GET /robots.txt HTTP/1.0\n\n")
while True:
        resp = s.recv(1024)
        if resp == "": break
        print(resp,)

# Close the connection when completed
s.close()
print("\ndone")

Error:

cg0546wq@smaug:~/Desktop/440$ python3 HTTPclient.py
Traceback (most recent call last):
  File "HTTPclient.py", line 11, in <module>
    s.send("GET /robots.txt HTTP/1.0\n\n")
TypeError: 'str' does not support the buffer interface

Can NOT use

  • urllib.request.urlopen
  • urllib2.urlopen
  • http
  • http.client
  • httplib
like image 675
CaseyJames22 Avatar asked May 29 '26 04:05

CaseyJames22


1 Answers

Sockets can only accept bytes, while you are trying to send it a Unicode string instead.

Encode your strings to bytes:

s.send("GET /robots.txt HTTP/1.0\n\n".encode('ascii'))

or give it a bytes literal (a string literal starting with a b prefix):

s.send(b"GET /robots.txt HTTP/1.0\n\n")

Take into account that data you receive will also be bytes values; you cannot just compare those to ''. Just test for an empty response, and you probably want to decode the response to str when printing:

while True:
    resp = s.recv(1024)
    if not resp: break
    print(resp.decode('ascii'))
like image 84
Martijn Pieters Avatar answered May 30 '26 18:05

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!