通过UNIX套接字连接Node.JS和PHP – EPIPE写入错误

我试图创build一个PHP和Node.JS创build的应用程序之间的桥梁。

Node.JS创build套接字并听取它,我的代码:

var net = require('net'), fs = require('fs'); var path = '/tmp/echo.sock'; fs.unlink(path, function () { var server = net.createServer(function(c) { console.log('server connected'); c.on('close', function() { console.log('server disconnected'); }); c.write('hello\r\n'); c.on('data', function(data) { console.log('Response: "' + data + '"'); c.write('You said "' + data + '"'); }); }); server.listen(path, function(e) { console.log('server bound on %s', path); }); }); process.on('uncaughtException', function (err) { console.log( "UNCAUGHT EXCEPTION " ); console.log( "[Inside 'uncaughtException' event] " + err.stack || err.message ); }); 

而我的PHP代码只是连接存在套接字和发送一些数据:

 $fp = fsockopen("unix:///tmp/echo.sock", -1, $errno, $errstr); if (!$fp) { return "ERROR: $errno - $errstr<br />\n"; } else { fwrite($fp, "Hello World <3"); $out = fread($fp, 8192); fclose($fp); return $out; // That code is in function. } 

一切都应该工作,但在Node.JS控制台,我看到的回应:

 server bound on /tmp/echo.sock server connected Response: "Hello World <3" UNCAUGHT EXCEPTION [Inside 'uncaughtException' event] Error: write EPIPE at exports._errnoException (util.js:745:11) at Object.afterWrite (net.js:763:14) server disconnected 

而在PHP中,我只看到第一条消息, hello 。 为什么以及如何解决这个问题?

尝试这个;

 <?php $fp = fsockopen("unix:///tmp/echo.sock", -1, $errno, $errstr); if (!$fp) { return "ERROR: $errno - $errstr<br />\n"; } else { $out = fread($fp, 8192); fwrite($fp, "Hello World <3"); $out2 = fread($fp, 8192); fclose($fp); echo $out; // That code is in function. echo $out2; // That code is in function. } ?> 

我知道问题在哪里 在PHP中,在写入数据之后,closures与pipe道的连接。 节点尝试写入响应,但它不能,因为PHP中的连接已closures。 所以,我刚刚添加检查是连接仍然。 当然,下面的这个不是在生产中使用,而是为了说明它是如何工作的。

Node.JS代码:

 var net = require('net'), fs = require('fs'); var path = '/tmp/echo.sock', toSend = 1, sended = 0; fs.unlink(path, function () { var server = net.createServer(function(c) { console.log('server connected'); c.on('close', function() { console.log('server disconnected'); }); c.write('hello\r\n'); c.on('data', function(data) { console.log('Response: "' + data + '"'); if( data == "IS_ALREADY_CLOSED" & toSend == sended ) { c.write('ALREADY_CLOSED'); return; } else { c.write('NOT_ALREADY_CLOSED'); return; } c.write('You said "' + data + '"'); sended++; }); }); server.listen(path, function(e) { console.log('server bound on %s', path); }); }); process.on('uncaughtException', function (err) { console.log( "UNCAUGHT EXCEPTION " ); console.log( "[Inside 'uncaughtException' event] " + err.stack || err.message ); }); 

在PHP中:

 $fp = fsockopen("unix:///tmp/echo.sock", -1, $errno, $errstr); if (!$fp) { return "ERROR: $errno - $errstr<br />\n"; } else { fwrite($fp, "Hello World <3"); do { $output = fread($fp, 8192); if($output == "ALREADY_CLOSED") break; elseif( $output == "NOT_ALREADY_CLOSED" ) continue; echo $output . "\n"; fwrite($fp, "IS_ALREADY_CLOSED"); } while(true); fclose($fp); }