如何创建侦听文件描述符的Python套接字服务器?

2024-05-15 07:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让Javascript(Nodejs)应用程序与Python应用程序通信。

我使用绑定到本地主机的套接字和特定端口获得something working

为了使事情更简单(例如,当部署到不允许我监听多个端口的环境时),我想将实现更改为使用绑定到文件描述符的套接字。

我到处找,但我找到的所有例子都使用端口。

基本上,我需要Python服务器计数器部分到this example from the Nodejs docs(指定路径的版本):

var client = net.connect({path: '/tmp/echo.sock'}

有人能提供一个简单的例子,显示,创建和绑定一个文件描述符套接字,并在其上处理数据和/或指向正确的方向吗?


Tags: 文件端口服务器应用程序环境部署nodejs计数器
1条回答
网友
1楼 · 发布于 2024-05-15 07:21:17

我修改了this nice example一点(例如,python服务器必须监听TCP,而不是UDP套接字,以便与nodejs客户端兼容)。

我在这里发布python服务器和nodejs客户端代码以供参考:

Python服务器:

import socket
import os, os.path
import time

sockfile = "./communicate.sock"

if os.path.exists( sockfile ):
  os.remove( sockfile )

print "Opening socket..."

server = socket.socket( socket.AF_UNIX, socket.SOCK_STREAM )
server.bind(sockfile)
server.listen(5)

print "Listening..."
while True:
  conn, addr = server.accept()

  print 'accepted connection'

  while True: 

    data = conn.recv( 1024 )
    if not data:
        break
    else:
        print "-" * 20
        print data
        if "DONE" == data:
            break
print "-" * 20
print "Shutting down..."

server.close()
os.remove( sockfile )

print "Done"

Nodejs客户端:

使用npmlog获得彩色日志输出npm install npmlog

var net = require('net')
  , log = require('npmlog')
  , sockfile = './communicate.sock'
  ;

var client = net.connect( { path: sockfile });

client
  .on('connect', function () {
    log.info('client', 'client connected');
    client.write('hello server');
  })
  .on('data', function (data) {
    log.info('client', 'Data: %s', data.toString());
    client.end(); 
  })
  .on('error', function (err) {
    log.error('client', err);
  })
  .on('end', function () {
    log.info('client', 'client disconnected');
  })
  ;

相关问题 更多 >