制作简单的TCP_CLIENT时出现问题

时间:2017-04-15 07:28:22

标签: python tcpclient

问题在于,当我运行此代码来制作简单的客户端时,我会收到这样的错误。

import socket

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

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

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

# ➌ send some data
client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")

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

print response

我首先使用AF_INETSOCK_STREAM参数➊创建一个套接字对象。 AF_INET参数表示我们将使用标准IPv4地址或host_name,SOCK_STREAM表示这将是TCP客户端。然后,我们将客户端连接到服务器➋并向其发送一些数据➌。最后一步是接收一些数据并打印出响应。

运行时会发生此错误 回溯(最近一次调用最后一次):

File "C:\Users\engin\Desktop\TCP_client.py", line 10, in <module>
client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")  
TypeError: a bytes-like object is required, not 'str'

有什么问题?

1 个答案:

答案 0 :(得分:0)

您正在尝试使用Python3运行Python2-Code,因为print语句会导致首先导致SyntaxError。其次,你必须发送字节,而不是字符串:

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