Python3.3 HTML Client TypeError: 'str' does not support 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")

      

Mistake:

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

      

CANNOT use

  • urllib.request.urlopen

  • urllib2.urlopen

  • http

  • http.client

  • httplib

+3


source to share


2 answers


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

Encode strings in bytes:

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

      

or assign it a byte literal (string literal starting with a prefix b

):



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

      

Keep in mind that the data you receive will also matter bytes

; you cannot simply compare them with ''

. Just check for an empty answer and you probably want to decode the answer to str

when you print:

while True:
    resp = s.recv(1024)
    if not resp: break
    print(resp.decode('ascii'))

      

+8


source


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.google.com",80))

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

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

      



+1


source







All Articles