代码之家  ›  专栏  ›  技术社区  ›  Vlad Karelov

连接到我的电脑托管的本地node.js服务器,并通过usb连接的电话连接

  •  -1
  • Vlad Karelov  · 技术社区  · 2 年前

    我正在托管一个使用websockets的localserver node.js服务器,以及一个通过liveserver扩展的前端应用程序 这种情况发生在我的笔记本电脑上,它使用usb连接通过我的手机访问互联网,我想知道是否有可能,如果有,如何连接到我笔记本电脑所在的本地服务器 我试图在手机上打开它,方法是在shell中输入我从ipconfig获得的笔记本电脑的ip地址,然后打开了两个文件夹

    可以打开前端应用程序,但它没有连接到服务器,如果防火墙有问题? 还是别的什么?

    客户代码:

    const socket = io('ws://localhost:3500')
    
    function sendMessage(e) {
        e.preventDefault()
        const input = document.querySelector('input')
        if (input.value) {
            socket.emit('message', input.value)
            input.value = ""
        }
        input.focus()
    }
    
    document.querySelector('form').addEventListener('submit',sendMessage)
    
    // Listen for messages
    socket.on('message', (data) => {
        const li = document.createElement('li')
        li.textContent = data
        document.querySelector('ul').appendChild(li)
    })
    

    服务器代码:

    import { createServer } from "http"
    import { Server } from "socket.io"
    
    const httpServer = createServer()
    
    const io = new Server(httpServer, {
        cors: {
            origin: "*"
        }
    })
    
    
    io.on('connection', socket => {
        console.log(`User ${socket.id} connected`)
    
        socket.on('message', data => {
            console.log(data)
            io.emit('message', `${socket.id.substring(0,5)}: ${data}`)
    
        })
    })
    
    
    httpServer.listen(3500, () => console.log('listening'))
    
    
    
    

    我为3500端口设置了防火墙入站规则,但没有任何更改

    1 回复  |  直到 2 年前
        1
  •  -1
  •   Nihal    2 年前

    在您的客户端代码中, 更改第一行

    const socket = io('ws://localhost:3500')
    

    const socket = io('ws://<YOUR_PC_IPADRESS>:3500')
    

    这是因为您的手机正试图连接到本地主机,也就是环回地址。因此,它尝试连接到自己运行的websocket服务器。

    推荐文章