gpt4 book ai didi

python - 建立一个TCP聊天室并在线程处理中出错

转载 作者:行者123 更新时间:2023-12-03 12:07:18 25 4
gpt4 key购买 nike

使用套接字和线程建立TCP聊天室,但在线程处理中出错。
客户端是本地客户端,另一个是使用其他设备的客户端。
服务器日志发生错误
服务器端有句柄函数,它给出了错误,应该没有可迭代的套接字,所以我该怎么解决。
服务器端:

# Sending Messages To All Connected Clients
def broadcast(message):
for client in clients:
client.send(message)

# Handling Messages From Clients
def handle(client):
while True:
try:
# Broadcasting Messages
message = client.recv(1024)
broadcast(message)
except:
# Removing And Closing Clients
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast('{} left!'.format(nickname).encode('ascii'))
nicknames.remove(nickname)
break

# Receiving / Listening Function
def receive():
while True:
# Accept Connection
client, address = server.accept()
print("Connected with {}".format(str(address)))

# Request And Store Nickname
client.send('NICK_NAME'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
clients.append(client)

# Print And Broadcast Nickname
print("Nickname is {}".format(nickname))
broadcast("{} joined!".format(nickname).encode('ascii'))
client.send('Connected to server!'.encode('ascii'))

# Start Handling Thread For Client
thread = threading.Thread(target=handle, args=(client))
thread.start()

receive()
input('Press Enter to Close the Server.')
客户端:
# Listening to Server and Sending Nickname
def receive():
while True:
try:
# Receive Message From Server
# If 'NICK_NAME' Send Nickname
message = client.recv(1024).decode('ascii')
if message == 'NICK_NAME':
client.send(nickname.encode('ascii'))
else:
print(message)
except:
# Close Connection When Error
print("An error occured!")
client.close()
break

# Sending Messages To Server
def write():
while True:
message = '{}: {}'.format(nickname, input(''))
client.send(message.encode('ascii'))

# Starting Threads For Listening And Writing
receive_thread = threading.Thread(target=receive)
receive_thread.start()

write_thread = threading.Thread(target=write)
write_thread.start()
在服务器端连接到服务器时出现以下错误:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\Anil soni\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Anil soni\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
TypeError: handle() argument after * must be an iterable, not socket
使用python 3.8.5和VS代码
谢谢

最佳答案

在args中添加,起作用了!!!

thread = threading.Thread(target=handle, args=(client,))

关于python - 建立一个TCP聊天室并在线程处理中出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65505641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com