Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
893 views
in Technique[技术] by (71.8m points)

string - Python Socket Send Buffer Vs. Str

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

The error:

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.

Any help would be appreciated,

Stephen

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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

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").


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...