我需要创建一个可以与CasparCG服务器通信的web应用程序。服务器接受具有基本IP和端口的TCP连接。然后,通过连接发送字符串,然后将触发内容。
在使用PHP作为这方面的主要通信工具时,我遇到了一个两难的问题,因为每次PHP用fread读取响应时,它都会断开与服务器的连接。脚本结束,因此连接终止。
我对任何语言的这部分PHP或TCP连接几乎没有经验。我不知道断开是否会影响整体性能,使得对C# TCP连接的每个请求都会延迟,当应用程序关闭或连接中止时,该连接似乎能够保持活动和断开连接。这就是我读到关于node.js的原因。
现在,对于这样一个应用程序来说,更好的选择是使用Node.js作为PHP吗?我已经有了一个很好的基础,可以从AngularJS + PHP开始,但问题是PHP。我没有使用node.js的经验,但我愿意尝试一下。
发布于 2016-04-02 18:33:50
是的,我建议你使用Node.js。你可以拿起网络模块。
var s = require("net");
var cn = s.createConnection({port: YourPortHere, host: YourHostHere}, callback); // createConnection and connect should be the same (cn is instance of net.Socket)
function callback(){
// Called when the connection is ready and so cn can be used
}
cn.on("data", function(data){
// Handle messages received by server (data is instance of Buffer)
if(data.toString("ascii") == "ping"){
s.write("pong!");
}
});
cn.on("end", function(){
// Disconnected
});正如你所看到的,使用起来真的很简单。注意:如果需要发送或解析特殊字符,可以更改编码,例如,在接收回调的第10行:
if(data.toString("utf8") == "èùà") // BTW, the parameter is usually set by default to utf8, so there is no need to provide that, in theory.发送特殊字符
cn.setEncoding("utf8");https://stackoverflow.com/questions/36376936
复制相似问题