python socket通信中的bytes类型问题

change丶 2016-10-14 10:57:43
我在写一个python socket通信时遇到了一个问题

服务器采用的asyncore.dispatcher来接收连接
用asyn_chat的一个子类来处理接受到的数据

服务器端代码:
from asyncore import dispatcher
from asynchat import async_chat
import socket,asyncore
PORT = 5005
class ChatSession(async_chat):
def __init__(self,sock):
async_chat.__init__(self,sock)
self.set_terminator("\r\n")
self.data = []
def collect_incoming_data(self,data):
self.data.append(data)
def found_terminator(self):
line = ''.join(self.data)
self.data = []
print(line)
class ChatServer(dispatcher):
def __init__(self,port):
dispatcher.__init__(self)
self.create_socket(socket.AF_INET,socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind(('',port))
self.listen(5)
self.session = []
def handle_accept(self):
conn,addr = self.accept()
print('Connection attempt from ',addr[0])
self.session.append(ChatSession(conn))
#print(self.session)
if __name__ == '__main__':
s = ChatServer(PORT)
print('Waiting Connection...')
try:asyncore.loop()
except KeyboardInterrupt:print('')

这里用重写的collect_incoming_data函数来接收client发送的内容

客户端采用的是一般的socket.connect和socket.send方法来建立连接和发送数据
客户端代码:
import socket
s = socket.socket()
host = socket.gethostname()
port = 5005
s.connect((host,port))
word = input('say something to your friend!\n')
while word:
word = bytes(word.encode())
s.send(word)
word = input('say something to your friend!\n')

客户端发送前对内容进行了encode对str内容转化了bytes 这边没什么问题
但是发送过去以后 服务器出现这样的错误
error: uncaptured python exception, closing channel <__main__.ChatSession connected 192.168.43.85:61536 at 0x173f530> (<class 'TypeError'>:a bytes-like object is required, not 'str' [C:\Users\tracy\AppData\Local\Programs\Python\Python35-32\lib\asyncore.py|read|83] [C:\Users\tracy\AppData\Local\Programs\Python\Python35-32\lib\asyncore.py|handle_read_event|423] [C:\Users\tracy\AppData\Local\Programs\Python\Python35-32\lib\asynchat.py|handle_read|161])

请问这是什么情况,我发送的时候不是已经将内容转化为bytes型了吗
...全文
542 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
sprawling 2016-10-15
  • 打赏
  • 举报
回复

你用2.7试试吧,这个是没有问题的.
raining 2016-10-15
  • 打赏
  • 举报
回复
服务端set_terminator的参数需要 bytes 客户端 encode() 后已经是bytes了.

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧