English 中文(简体)
从PHP向Node传递信息。 j)
原标题:Sending messages from PHP to Node.js
  • 时间:2012-04-06 20:37:40
  •  标签:
  • php
  • node.js

如何从营地向 no发出信息? 我有一台中继服务器,运行地点和网点。

当用户完成交易(通过php)时,我就向Node.js发出信息。 之后,Node将通过电话链接向客户提供最新情况。

什么是将少量数据从营地传送到点子的好办法。 j 不打败 no子的表现?

最佳回答

该建议似乎是指像任何其他客户一样,通过吉大港定居地安置点交汇点。 您可以通过吉卜赛人协会在格林纳达使用“URL”与世隔绝。

http://groups.google.com/group/socket_io/browse_thread/74a76896d2bccc/216933a076ac25?pli=1

In particular, see this post from Matt Pardee

I faced a similar problem with wanting to keep users informed of a new note added on to a bug, and similar notifications that could really only be effectively sent from PHP to my Node server. What I did follows (apologies if this gets all garbled and unformatted in sending, if it does, I d be happy to paste the code somewhere else): First, you ll need to use cURL from PHP. I wrote a function for my class like this:

function notifyNode($type, $project_id, $from_user, $data) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,  http://127.0.0.1 );

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array( Expect: ));
    curl_setopt($ch, CURLOPT_PORT, 8001);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);

    curl_setopt($ch, CURLOPT_POST, true);

    $pf = array( f  => $type,  pid  => $project_id,  user_from  => $from_user, 
              data  => array());

    foreach($data as $k => $v) {
        $pf[ data ][$k] = $v;
    }

    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($pf));

    curl_exec($ch);
    curl_close($ch);
}

You ll notice that I send the cURL request on the same server since both PHP and NodeJS are running there, your mileage may vary. The port I set this code to connect to is 8001 (this is the port my Node server is running on, and the port the socket.io server connects to). This sends a HTTP POST request with the post field encoded. This is all pretty standard cURL stuff.

在您的诺言中,你也许有这样的东西:

var server = http.createServer(function(req, res) {});
server.listen(8001);
var io = io.listen(server, { transports: [ websocket ,  flashsocket ,  xhr-polling ] });

...

well what we ll do here is expand on the http.createServer part, to listen for connections coming from our local host ("127.0.0.1"). The createServer code then becomes:

var server = http.createServer(function(req, res) {
    // Check for notices from PHP
    if(res.socket.remoteAddress ==  127.0.0.1 ) {
        if(req.method ==  POST ) {
            // The server is trying to send us an activity message

            var form = new formidable.IncomingForm();
            form.parse(req, function(err, fields, files) {

                res.writeHead(200, [[ "Content-Type", "text/plain"]
                        , ["Content-Length", 0]
                        ]);
                res.write(  );
                res.end();

                //sys.puts(sys.inspect({fields: fields}, true, 4));

                handleServerNotice(fields);                
            });
        }
    }
});

您可以履行你的职责。 服务器诺言功能。

function handleServerNotice(data) {
        ...
}

etc etc. I haven t tested this in a while, and in fact that code block was commented out on my node server, so I hope what I ve pasted here works - in general this concept is proven and I think it ll work for you. Anyway just wanted to be sure you knew it s been a few months so I m not sure exactly why I commented out. The code I wrote took a little research -- like setting the Expect: header in cURL -- and I was pretty excited when it finally worked. Let me know if you need any additional help.

最好

Matt Pardee

问题回答

A bit late, but you could communicate with your node client using the Redis Pub/Sub mechanism in a very simple and effective way. All you need to do is install redis on your server.

在营地方面,最初的Redis公司随后发表了信息。

$purchase_info = json_encode(array( user_id  =>$user_id,
          purchase_information =>array( item => book , price => 2$ ));

$this->redis->publish( transaction_completed , $purchase_info);

no

var redis = require( redis );
var purchase_listener = redis.createClient();
purchase_listener.subscribe( transaction_completed );
purchase_listener.on( message , function(channel, message){
    var purchase_data = JSON.parse(message);
    user_id = purchase_data.user_id;
    purchase_info = purchase_data.purchase_information;
    // Process the data
    // And send confirmation to your client via a socket connection
})

www.un.org/spanish/ecosoc 这是否可衡量? (针对@mohan-singh)

When talking about scalability you need to think about your infrastructure s architecture and your particular needs but here s a quick answer : I ve been using a variant of this mechanism on a high traffic real-time application without problems but here s what you should be careful about:

  1. Redis PUB/SUB并不是一个排队系统,这意味着如果你的节点程序推翻发出的所有电文,就会丢失。

  2. 如果你们有1个以上的订阅者,他们都会收到同样的信息,并处理这些信息,那么,如果你听从处理你实时逻辑的同一重新分类程序,就会小心谨慎。 (尽管如此,容易走过路)

这一制度的一点是,你不需要给你现有的基础设施增加任何东西,而且能够立即启动,它速度非常快,它完全像一个吉大港定居地的服务器。

下面是你们选择更可衡量的选择:

  1. Using a self-hosted fast messaging queue server (ActiveMQ, RabbitMQ, beanstalkd ... ) server to handle your messaging logic between php and node, these tend to be fast but as the load increases you lose a bit of performance, and have to maintain/scale your messaging servers, and take care of duplication across regions which is not an easy and enjoyable thing (depending on what you enjoy doing).
  2. Using a hosted messaging queue server (IronMQ, SQS...) Some of these(IronMQ) are pretty fast and will be great for your use case but introduce some (minor) complexity to your codebase.
  3. Building a messaging queue with Redis with clustered node servers : https://davidmarquis.wordpress.com/2013/01/03/reliable-delivery-message-queues-with-redis/
  4. Using HTTP inside a VPN to communicate with node servers. Once you see your traffic spiking you will only need to load-balance your node servers and add as much stateless servers as you need and send POST messages to that load balancer.

The point of this lengthy edit is that there is no such thing as a magic scalable solution, you need to weigh your options and see which one works the best for your use case. In my opinion, if you re starting to build your first iteration now, choose any option that you re comfortable with, write very clean code and when you start scaling it will be very easy to change, this is what I ve done :)

I found such problem can be solved simply by using the Express framework. Let s suppose php sends a json message to the node server and the server replies with ok.

页: 1

var app = require( express )();
var http = require( http ).Server(app);
var io = require( socket.io )(http);
var bodyParser = require( body-parser )
app.use(bodyParser.json());

app.post( /phpcallback , function(req, res) {
    var content = req.body;
    console.log( message received from php:   + content.msg);
    //to-do: forward the message to the connected nodes.
    res.end( ok );
});

http.listen(8080, function(){
  var addr = http.address();
  console.log( app listening on   + addr.address +  :  + addr.port);
});

测试。 php

<?php

$data = array("name" => "Robot", "msg" => "Hi guys, I m a PHP bot !");                                                                    
$data_string = json_encode($data);

$ch = curl_init( http://localhost:8080/phpcallback );                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
     Content-Type: application/json ,                                                                                
     Content-Length:   . strlen($data_string))                                                                       
);                                                                                                                   

echo curl_exec($ch)."
";
curl_close($ch);

?>

在这里,我们还有一个更为详细的例子,即:一个营地的文字可以向某个具体聊天室的使用者传递信息。

https://github.com/lteu/chat


我个人对红斯办法的印象:umber。 你们需要管理阿帕奇、诺德JS和红利,三个服务器也一样。 而PubSub机制与提要有很大不同。 io,因此,你需要看看这是否符合你现有的法典。

我正在寻求一种真正简单的方法,使PHP能够发送一份书状。 io 给客户的信息。

这并不需要任何额外的PHP图书馆——它只是使用袖珍。

不要试图连接像其他许多解决办法一样的网络电话接口,而只是连接点子服务器,使用<代码>.on(数据)接收信息。

然后,socket.io可向客户传送。

Detect a connection from your PHP server in Node.js like this:

//You might have something like this - just included to show object setup
var app = express();
var server = http.createServer(app);
var io = require( socket.io ).listen(server);

server.on("connection", function(s) {
    //If connection is from our server (localhost)
    if(s.remoteAddress == "::ffff:127.0.0.1") {
        s.on( data , function(buf) {
            var js = JSON.parse(buf);
            io.emit(js.msg,js.data); //Send the msg to socket.io clients
        });
    }
});

在这里,根据令人难以置信的简单的《加拿大法典》——我把它总结为一项功能——你可以找到更好的东西。

Note that 8080 is the port to my Node.js server - you may want to change.

function sio_message($message, $data) {
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    $result = socket_connect($socket,  127.0.0.1 , 8080);
    if(!$result) {
        die( cannot connect  .socket_strerror(socket_last_error()).PHP_EOL);
    }
    $bytes = socket_write($socket, json_encode(Array("msg" => $message, "data" => $data)));
    socket_close($socket);
}

你们可以这样做:

sio_message(“聊天信息”),“Hello from PHP>;

你们还可以寄出各种阵列,这些阵列被转换为 j,并传给客户。

sio_message ("DataUpdate”,Array(“Data1” =>“ingthing”、“Data2” =>“ing others”);

这是贵国客户从服务器获取合法信息的“信任”的有用方法。

如果没有数百名客户查询数据库,你也可以通过更新数据库的PHP。

我希望我更早地看到这一点——希望能帮助!

Step 1. Get the PHP Emitter: https://github.com/rase-/socket.io-php-emitter

$redis = new Redis(); // Using the Redis extension provided client
$redis->connect( 127.0.0.1 ,  6379 );
$emitter = new SocketIOEmitter($redis);
$emitter->emit( new question ,  <b>h<br/>tml</b> );

在您的指数中加上这一点。 j)

var redis = require( socket.io-redis );
io.adapter(redis({ host:  localhost , port: 6379 }));
io.on( connection , function(socket){
    socket.on( new question , function(msg) {
        io.emit( new question , msg);
    });
});

在您的指数中增加这样的内容。 html

socket.on( new question , function(msg) {
    $( body ).append( msg );
});




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签