2
我正在编程一个基本的聊天程序。这样做的目标是首先通过启动server.py脚本来设置服务器,然后在后台运行该服务器。然后用户启动client.py脚本并选择一个名称,然后开始键入一条消息并发送它。问题是当我尝试发送它时会返回这个错误。Python错误:无法将字节隐式转换为字符串
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()
所以,如果你有任何想法如何解决这个问题将不胜感激也有一个侧面的问题是有没有办法让接收线程一直运行,所以它主动更新聊天?