python2.7与python3.5关于TCP通讯样例

        关于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'

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值