我稍微修改了这个很好的示例(例如,python 服务器必须侦听 TCP 而不是 UDP 套接字才能与 nodejs 客户端兼容。
我在这里发布 python 服务器和 nodejs 客户端代码以供参考:
蟒蛇服务器:
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');
})
;