关于python2.7及python3.5之间在网络通讯方面出现一定的差异,尽管差异比较小,但对于新手或者没有踩过此坑的人可能会感觉到困惑。
python3.5 服务端
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 14:39:04 2017
@author: linxiaojie
"""
from socket import *
import threading
bind_ip = "0.0.0.0"
bind_port = 9999
server = socket(AF_INET, SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
# 定义一个服务端处理接口,简单支持并发接收client的请求
def handle_client(client_socket):
request = client_socket.recv(1024).decode()
print(request)
client_socket.send("hi,client,".encode())
client_socket.close()
while True:
client,addr = server.accept()
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()
python3.5 客户端:
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 14:21:20 2018
@author: linxiaojie
"""
from socket import *
host = "127.0.0.1"
port = 9999
client = socket(AF_INET, SOCK_STREAM)
client.connect((host, port))
client.send("hi,server".encode())
client.send("hi,server".encode())
response = client.recv(4096)
print(response)
client.close()
python2.7 服务端:
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 14:45:04 2017
@author: linxiaojie
"""
from socket import *
import threading
bind_ip = "0.0.0.0"
bind_port = 9999
server = socket(AF_INET, SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
# 定义一个服务端处理接口,初步支持并发接收client的请求
def handle_client(client_socket):
request = client_socket.recv(1024)
print request
client_socket.send("hi,client,")
while True:
client,addr = server.accept()
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()
python2.7 客户端:
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 14:45:20 2017
@author: linxiaojie
"""
from socket import *
host = "127.0.0.1"
port = 9999
client = socket(AF_INET, SOCK_STREAM)
client.connect((host, port))
client.send("hi,server!!")
response = client.recv(4096)
print response; client.close()
从上面四小段代码可以看出,通讯方面的接收数据及发送数据间存在差异,python3.5在发送数据时,先要对str进行encode,而接收数据后使用decode进行解码,而python2.7在发送数据及接数据都不需要做此方面的处理。原因在于python3.5在数据处理方面使用的是bytes类型,而在python2.7在数据处理方面使用的是string类型。因此python3.5在发送及接收数据时需要将str转换成bytes时需要使用encode()及decode()。
python3.5若是没使用encode()及decode()对字符串进行bytes类型转换,则出现如下错误:
TypeError: a bytes-like object is required, not 'str'