首页 > 解决方案 > Python Socket 服务器不接受来自本地 WIFI 网络外部的连接

问题描述

我创建了一个简单的消息传递应用程序,并且我正在尝试制作它,以便我家庭网络之外的人可以加入。我端口转发了正在运行的机器。我确保 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() 

标签: pythonpython-sockets

解决方案


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

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

以下是这些步骤的摘要:

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

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


推荐阅读