嘿,所以我想检测昵称是否已经在昵称列表中。如果它已经在那里,向客户端发送一条消息,以便它生成一个新的昵称。问题是我相信服务器没有发送消息。
服务器代码:
try:
client.send("--%||NICK||%--".encode('utf-8'))
nickname = client.recv(1024).decode('utf-8')
#Check if the same user is connected.
if not nickname in nicknames:
print('User is not in nicknames')
print(f'[Server] {nickname} has connected to the server')
#This line doesn't make anything yet, still here to remind me to redo the broadcast func.
broadcast(f'[Server] {nickname} joined the room!\n'.encode('utf-8'))
nicknames.append(nickname)
thread = threading.Thread(target = handle, args=(client,))
thread.start()
else:
print('User is already on nicknames')
#Client will generate a new discrim and will tell the user to retry connecting.
print('[Server] Sending user ALREADYONLINE message.')
try:
client.send('--%||ALREADYONLINE||%--'.encode('utf-8'))
except Exception as e:
print('An error occured sending ALREADYONLINE:')
print(e)
#Get index for client and nickname
index = clients.index(client)
nickname = nicknames[index]
print(f'[Server] {nicknames[clients.index(client)]} disconnected from the server.')
#Remove client object and nickname from lists.
clients.remove(client)
#Close connection on client
客户端代码:
def receive(self):
try:
message = self.sock.recv(1024).decode('utf-8')
if message == '--%||NICK||%--':
print('--%||NICK||%--')
self.sock.send(settings.get_setting(
'nickname').encode('utf-8'))
elif message == '--%||ALREADYONLINE||%--':
print('--%||ALREADYONLINE||%--')
messagebox.showerror(
title='Nickname Error', message=f"There is already an user connected with the nickname: \"{settings.get_setting('nickname')}\". \n We've changed your last 4 numbers to allow your connection to the server.")
self.sock.close()
else:
print('Message is not nickname')
except Exception as e:
print(e)
客户端输出:
--%||NICK||%--
服务器输出:
[Server] server_data folder exists.
Server started
[Server] Connected with ('ip', 'address')
User is already on nicknames
[Server] Sending user ALREADYONLINE message.
[Server] MrFellah el dev#1927 disconnected from the server.
我已尝试更改消息发送的字符串,打印任何错误,但似乎仍然没有收到消息。但是客户端按预期关闭了连接。
另外,抱歉我的代码杂乱无章:)
答案 0 :(得分:0)
编辑:我解决了,我在客户端函数上遗漏了一个 while True
循环。