【问题标题】:Python Socket Server Isn't Accepting Connections From Outside The Local WIFI NetworkPython Socket 服务器不接受来自本地 WIFI 网络外部的连接
【发布时间】: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


【解决方案1】:

可能不是您正在寻找的答案。但是这里的隧道可以帮到你。

我是从 Fireship 的这个视频中了解到他们的。 https://www.youtube.com/watch?v=SlBOpNLFUC0

以下是步骤摘要:

  1. 使用CloudFlare TunnelsNgrok
  2. 下载 cloudflare 隧道 cli 工具
  3. 运行隧道命令并将其指向您要服务的本地主机端口

它会输出一个网址,现在任何人都可以在互联网上查看您的本地主机

【讨论】:

    猜你喜欢
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 2019-07-19
    相关资源
    最近更新 更多