Python新手遇到TCP客户端问题

时间:2016-12-21 03:31:08

标签: python tcp byte typeerror

基本上我只是开始使用python网络和python而且我无法让我的TCP客户端发送数据。它说:

Traceback (most recent call last):
  File "script.py", line 14, in <module>
    client.send(data) #this is where I get the error
TypeError: a bytes-like object is required, not 'str'

代码如下:

import socket

target_host = "www.google.com"
target_port = 80 

#create socket object
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#connect the client
client.connect((target_host,target_port))

#send some data
data = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n"
client.send(data) #this is where I get the error

#receive some data
response = client.recv(4096)

print(response)

提前感谢您的帮助!

4 个答案:

答案 0 :(得分:0)

如果您使用的是python2.x,那么您的代码是正确的。在python2 socket.send()的文档中,需要一个字符串参数。但是如果你使用的是python3.x,你会发现socket.send()需要一个bytes参数。因此,您必须使用str.encode()将字符串https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood4& 转换为字节。所以你的代码可能会像这样。

data

答案 1 :(得分:0)

您可能正在使用Python 3.X. socket.send()期望一个字节类型参数,但data是一个unicode字符串。您必须使用str.encode()方法对字符串进行编码。同样,您可以使用bytes.decode()来接收数据:

import socket

target_host = "www.google.com"
target_port = 80

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host,target_port))

data = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n"
client.send(data.encode('utf-8'))

response = client.recv(4096).decode('utf-8')

print(response)

答案 2 :(得分:0)

所以我用utf-8对数据进行了编码,正如少数人所建议的那样,并重写了修复奇怪语法错误的代码。现在我的代码完美无缺。感谢所有发帖但特别是@FJSevilla的人。工作代码如下:

import socket

target_host = "www.google.com"
target_port = 80

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host,target_port))

data = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n"
client.send(data.encode('utf-8'))

response = client.recv(4096).decode('utf-8')

print(response)

答案 3 :(得分:0)

使用Python 3.7的另一个建议是在消息中添加字母“ b”。例如:

s.send(b"GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")
import socket

t_host = "www.google.com"
t_port = 80

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((t_host, t_port))

s.send(b"GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")

response = s.recv(4096)

print(response)
相关问题