我正在尝试在用PHP创建的应用程序和Node.JS之间建立桥梁。
Node.JS创建套接字并监听它,我的代码是:
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中,我在写入数据后关闭了与管道的连接。Node尝试编写响应,但不能写响应,因为PHP中的连接已关闭。因此,我刚刚添加了检查连接是否仍然正常。当然,下面的代码不会在生产中使用,而只是为了说明其工作原理。
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句