【发布时间】:2021-12-09 12:01:54
【问题描述】:
我创建了一个简单的消息传递应用程序,我正在尝试制作它,以便我家庭网络之外的人可以加入。我端口转发了正在运行的机器。我确保 Iv4 和端口与 Xfinity 网关上的设置匹配。即使那样,它仍然无法在我的家庭网络之外工作。我还需要做些什么才能让它发挥作用吗?
这是服务器代码。不知道有没有用。
import threading
import socket
host = "IV4 HERE"
port = PORT HERE
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicknames = []
def brodcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
message = client.recv(1024)
brodcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
brodcast(f'''
{nickname} left the chat'''.encode('ascii'))
nicknames.remove(nickname)
break
def recive():
while True:
client, address = server.accept()
print(f"Connected with {str(address)}")
client.send('NICK'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print(f'{nickname} joined the chat!')
brodcast(f'{nickname} joined the chat!'.encode('ascii'))
client.send('Connected to the chat'.encode('ascii'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
recive()
【问题讨论】:
-
路由器上的端口转发是等式的一半。您是否也配置了系统防火墙?这咬了我好几次。
-
您应该始终将侦听套接字绑定到 0.0.0.0 而不是任何特定的 IP 地址,除非您确切知道为什么要这样做。
标签: python python-sockets