Python3:socket:TypeError:%不支持的操作数类型:'bytes'和'bytes'

时间:2015-06-17 07:26:58

标签: sockets python-3.x

我尝试使用python socket包来实现echo服务器。但它不断出现错误:TypeError: unsupported operand type(s) for %: 'bytes' and 'bytes',我的代码中是否有任何错误?

这是错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/threading.py", line 921, in _bootstrap_inner
        self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/threading.py", line 869, in run
        self._target(*self._args, **self._kwargs)
  File "do_tcp_server.py", line 25, in tcplink
        sock.send(b'Hello, %s!' % data)
TypeError: unsupported operand type(s) for %: 'bytes' and 'bytes'

这是我的代码:

server.py:

#!/usr/bin/env python3
# coding: utf-8

"A simple server"

import socket
import threading
import time

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(("127.0.0.1", 9999))

s.listen(5)
print("Lsitening...")

def tcplink(sock, addr):
    print('Accept new connection from %s:%s...' % addr)
    sock.send(b'Welcome!')
    while True:
        data = sock.recv(1024)
        time.sleep(1)
        if not data or data.decode('utf-8') == 'exit':
            break
        sock.send(b'Hello, %s!' % data)
    sock.close()
    print('Connection from %s:%s closed.' % addr)

while True:
    sock, addr = s.accept()
    # create a thread to handle it
    t = threading.Thread(target=tcplink, args=(sock, addr))
    t.start()

client.py:

#!/usr/bin/env python3
# coding: utf-8

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# establish connection:
s.connect(('127.0.0.1', 9999))
# receive Welcome data:
print(s.recv(1024).decode('utf-8'))
for data in [b'Michael', b'Tracy', b'Sarah']:
    # send data
    s.send(data)
    print(s.recv(1024).decode('utf-8'))
s.send(b'exit')
s.close()

3 个答案:

答案 0 :(得分:1)

普通字符串格式不能用于bytes。我认为解决这个问题的方法是 - 你必须首先生成一个字符串,对其进行格式化,然后使用适当的编码将其转换为字节。因此,以下更改应该有效

变化

sock.send(b'Hello %s!' % data) 

reply = 'Hello %s!' % data) 
sock.send(bytes(reply, 'utf-8'))

基本上这是由于python3中字符串和字节之间的差异。 [Best way to convert string to bytes in Python 3?已经了解了更多细节。

那应该有用。

答案 1 :(得分:1)

实际上,此错误仅发生在Python 3.4上,我发现Python 3.5+通过Travis CI传递了它。因此对于Python 3.4和Python 2.7:

更改

sock.send(b'Hello %s!' % data) 

reply = 'Hello %s!' % data) 
sock.send(reply.encode('utf-8'))

Python 2和Python 3均支持s.encode('utf-8')

请参阅https://stackoverflow.com/a/45269679/12074740

注意:Python 2不支持bytes(reply, 'utf-8')

我希望它能帮助像我这样希望代码在Python 2和Python 3上都能工作的人

答案 2 :(得分:0)

答案@gaabhijit gaves很好。我只想假设有问题的代码来自这里(enter link description here) 否则,当python_3.5到来时,b'%s'可以是右()。