Python 套接字发送缓冲区对比.强度 [英] Python Socket Send Buffer Vs. Str

查看:43
本文介绍了Python 套接字发送缓冲区对比.强度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让一个基本服务器(从 Beginning Python 复制)发送一个 str.

I am trying to get a basic server (copied from Beginning Python) to send a str.

错误:

c.send( "XXX" )
TypeError: must be bytes or buffer, not str

它在酸洗对象时似乎有效.我找到的所有例子,似乎都可以发送字符串没问题.

It seems to work when pickling an object. All of the examples I found, seem to be able to send a string no problem.

任何帮助将不胜感激,

斯蒂芬

import socket  
import pickle  

s = socket.socket()

host = socket.gethostname()

port = 80

s.bind((host, port))

s.listen(5)

while True:  
    c, addr = s.accept()  
    print( "Got Connection From ", addr )  
    data = pickle.dumps(c)  
    c.send( "XXX" )  
    #c.send(data)  
    c.close()

推荐答案

您似乎尝试在 Python 3 中使用 Python 2.x 示例,但您发现了这些 Python 版本之间的主要差异之一.

It seems you try to use Python 2.x examples in Python 3 and you hit one of the main differences between those Python version.

对于 Python <3 'strings' 实际上是二进制字符串,'unicode objects' 是正确的文本对象(因为它们可以包含任何 Unicode 字符).

For Python < 3 'strings' are in fact binary strings and 'unicode objects' are the right text objects (as they can contain any Unicode characters).

在 Python 3 中,unicode 字符串是常规字符串"(str),字节字符串是单独的对象.

In Python 3 unicode strings are the 'regular strings' (str) and byte strings are separate objects.

低级 I/O 只能用数据(字节串)完成,不能用文本(字符序列)完成.对于 Python 2.x str 也是二进制数据"类型.在 Python 3 中不再是它,应该使用特殊的数据"对象之一.对象被腌制为这样的字节字符串.如果您想在代码中手动输入它们,请使用b"前缀(bXXX"而不是XXX").

Low level I/O can be done only with data (byte strings), not text (sequence of characters). For Python 2.x str was also the 'binary data' type. In Python 3 it is not any more and one of the special 'data' objects should be used. Objects are pickled to such byte strings. If you want to enter them manually in code use the "b" prefix (b"XXX" instead of "XXX").

这篇关于Python 套接字发送缓冲区对比.强度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆