![](/img/trans.png)
[英]Python Socket Programming: sending and receiving int data between server and client?
[英]Python Server not sending data/Client not receiving
嘿,所以我想检测昵称是否已经在昵称列表中。 如果它已经在那里,向客户端发送一条消息,以便它生成一个新的昵称。 问题是我相信服务器不发送消息。
服务器代码:
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)
客户 output:
--%||NICK||%--
服务器 output:
[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.
我尝试更改消息发送的字符串,打印任何错误,但似乎它没有收到消息。 但是客户端按预期关闭了连接。
另外,对不起我杂乱无章的代码:)
编辑:我解决了,我在客户端 function 上错过了一个while True
循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.