Python错误:无法隐式地将字节转换为字符串

时间:2016-06-29 20:38:41

标签: sockets python-3.x server

我正在编写一个基本的聊天程序。这样做的目的是首先通过启动server.py脚本来设置服务器,然后让它在后台运行。然后,用户启动client.py脚本并选择一个名称,然后开始键入消息并发送它。问题是当我尝试发送它时会返回此错误。

Traceback (most recent call last):
  File "C:\Users\Hello\AppData\Local\Programs\Python\Python35-32\client.py", line 38, in <module>
    s.sendto(alias + ': ' + message.encode() , server)
TypeError: Can't convert 'bytes' object to str implicitly

这是server.py脚本---

import socket
import time

host = '127.0.0.1'
port = 47015

clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)

qutting = False
print("Server Started")

while not qutting:
    try:
        data, addr = s.recvfrom(1024)
        if 'Quit' in str(data):
            qutting = True
        if addr not in clients:
            clients.append(addr)
        print(time.ctime(time.time()) + str(addr) + ": :" + str(data))
        for client in clients:
            s.sendto(data, client)
    except:
        pass
s.close()

然后是client.py脚本----

import socket
import threading
import time


tLock = threading.Lock()
shutdown = False

def recieving(name, sock):
    while not shutdown:
        try:
            tLock.acquire()
            while True:
                data, addr = sock.recvfrom(1024)
                data.decode()
                print(str(data))
        except:
            pass
        finally:
            tLock.release()

host = '127.0.0.1'
port = 0

server = ("127.0.0.1", 47015)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)

rT = threading.Thread(target=recieving, args=('RecvThread', s))
rT.start()

alias = input("Name: ")
message = input(alias + "->")
while message != 'q':
    if message != '':
        s.sendto(alias + ': ' + message.encode() , server)
    tLock.acquire()
    message = input(alias + '->')
    tLock.release()
    time.sleep(0.2)

shutdown = True
rT.join()
s.close()

因此,如果你有任何想法如何解决这个问题,那么一个侧面的问题是,是否会有一种方法可以使接收线程一直运行以便主动更新聊天?

1 个答案:

答案 0 :(得分:0)

问题出在这一行:

s.sendto(alias + ': ' + message.encode() , server)

您正在将message转换为bytes,但之后您将未转换的字符串添加到bytes对象。这是一个无效的操作,正如错误消息告诉您的那样,因为bytes无法明确地转换为字符串。尝试编码整个事情:

s.sendto((alias + ': ' + message).encode() , server)