【问题标题】:How to use TCP in Node to interact with other applications如何在 Node 中使用 TCP 与其他应用程序交互
【发布时间】:2018-07-20 10:34:59
【问题描述】:

我是套接字新手,我想连接两个进程(仅在本地主机上)。我有我的 python 程序,它做了一些事情,需要将它的结果永久发送到用 javascript 编写的用户界面。我考虑过 Socket.IO,但据我所知,Socket.IO 位于 http 之上,而 python 套接字是 TCP 连接。甚至可以通过套接字连接javascript和python吗?

【问题讨论】:

    标签: javascript node.js python-3.x sockets socket.io


    【解决方案1】:

    您可以考虑使用 WebSocket,尽管对于仅本地的东西来说它可能是一个沉重的选择。文档在这里:https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API

    另外,您似乎正在使用 socket.io,也许您应该试试这个库:https://github.com/evanw/socket.io-python,它似乎做了一些与您的项目相关的事情。

    【讨论】:

      【解决方案2】:

      您可以使用 Node.js 核心 API 附带的 Net Module 创建 TCP 套接字服务器或作为客户端连接到现有的 TCP 服务器。

      如果您想创建一个新的 TCP 服务器,您可以使用 net.createServer() 或自己创建一个 new Server

      const {Server} = require('net')
      
      const server = new Server(socket=> {
        console.log('client connected')
      
        // Attach listeners for the socket
        socket.on('data', message => {
          console.log('message')
      
          // Write back to the client
          socket.write('world')     
        })
      
        // Send the client a message to disconnect from the server after a minute
        setTimeout(() => socket.write('disconnect'), 60000)
      
        socket.on('end', () => console.log('client disconnected'))
      })
      
      server.listen('localhost', () => console.log('listening'))
      

      如果您希望创建与现有服务器的客户端 TCP 连接,您可以使用 net.createConnection() 或创建 new Socket 并使用 socket.connect() 连接到 TCP 服务器。

      const {Socket} = require('net')
      
      const client= new Socket()
      
      client.connect('localhost', () => {
        console.log('connected to localhost')
      
        client.on('data', message => {
          if (message === 'disconnect') {
            console.log('disconnecting from localhost')
            client.end()
          } else {
            console.log(`Message from the Server: ${message}`)
          }
        })
      
        client.write('hello!')
      })
      

      【讨论】:

        【解决方案3】:

        我知道一个项目使用ZeroMQ messaging protocol 来做你感兴趣的事情。你应该考虑看看。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-25
          • 1970-01-01
          • 2012-12-26
          • 1970-01-01
          • 2012-06-09
          • 1970-01-01
          • 2011-09-18
          • 1970-01-01
          相关资源
          最近更新 更多