我刚开始用Python编写UDP服务器和客户端。我已经按照教程并添加了一些自己的知识来创建命令行聊天服务器。一切都按计划工作,除了一件事:当我的客户端向服务器发送消息时,服务器在实际消息前面用b'打印它。我的客户将他的消息发回给他,前面是b'。我已经尝试在客户端解码消息,但它从未发送过。我已经尝试在服务器将其发送回来时对消息进行解码,但它从不发送回客户端。我想删除它的原因是因为它破坏了我想要的程序。感谢您的任何帮助!下面是我的代码,首先是服务器,然后是客户端。在我的代码之后,我已经粘贴了一些输出,所以你可以看到我正在谈论的内容。
#Server
from socket import *
import time
address = input("IP Address: ")
port = input("Port: ")
clients = []
serversock = socket(AF_INET, SOCK_DGRAM)
serversock.bind((address, int(port)))
serversock.setblocking(0)
quitting = False
print("Server is up and running so far.")
while not quitting:
try:
data, addr = serversock.recvfrom(1024)
if "Quit" in str(data):
quitting = True
if addr not in clients:
clients.append(addr)
print(time.ctime(time.time()) + str(addr) + ": :" + str(data))
for client in clients:
serversock.sendto(data, client)
except:
pass
serversock.close()
#Client
from socket import *
import threading
import time
tLock = threading.Lock()
shutdown = False
def receiving(name, sock):
while not shutdown:
try:
tLock.acquire()
while True:
data, addr = sock.recvfrom(1024)
print(str(data))
except:
pass
finally:
tLock.release()
address = input("IP Address: ")
port = 0
server = address, 6090
clientsock = socket(AF_INET, SOCK_DGRAM)
clientsock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
clientsock.bind((address, int(port)))
clientsock.setblocking(0)
rT = threading.Thread(target=receiving, args=("RecvThread", clientsock))
rT.start()
nick = input("How about we get you a nickname: ")
message = input(nick + "> ").encode()
while message != "q":
if message != "":
clientsock.sendto(nick.encode() + "> ".encode() + message, server)
tLock.acquire()
message = input(nick + "> ").encode()
tLock.release()
time.sleep(0.2)
shutdown = True
rT.join()
clientsock.close()
服务器如何收到消息: Sun Oct 30 18:23:22 2016('192.168.1.66',61249):: b'jake>杰克'
答案 0 :(得分:4)
您发送/接收的数据是字节数组,因此您需要解码它们以获得不带b''
的字符串。
您只需使用print(data.decode())
即可获得正确的输出。如果您未指定任何编码,则默认行为是使用utf8(有关详细信息,请参阅python doc)