简体   繁体   English

Socket.io和PHP

[英]Socket.io and PHP

Can someone please tell me if socket.io is only useful if the page your clients will use is a HTML page. 有人可以告诉我socket.io是否仅在您的客户使用的页面是HTML页面时有用。

I want to create a node server that can push events to my existing PHP pages. 我想创建一个可以将事件推送到现有PHP页面的节点服务器。

The pages are different and not suffixed with html. 这些页面是不同的,并且没有html后缀。

All the examples I read use Chatroom examples with Index.html etc. 我阅读的所有示例都使用带有Index.html等的Chatroom示例。

I simply want to know if what I want to do is even feasible. 我只是想知道我想做的事是否可行。

Many thanks in advance. 提前谢谢了。

When you write a php page the output is html. 当您编写php页面时,输出为html。 I hope that answers your question 我希望能回答您的问题

PHP and socket.io work together. PHP和socket.io一起工作。 The only difference between doing it with html and with PHP is the way you link the two together (the common tutorial shows a way that only works with html, but there is another way that works with both html and php). 使用html和PHP进行操作的唯一区别是将两者链接在一起的方式(通用教程显示了仅适用于html的方法,但还有另一种适用于html和php的方法)。

Try something like this (from a similar answer of mine, https://stackoverflow.com/a/25189436/3842050 ): 尝试这样的事情(从我的类似答案https://stackoverflow.com/a/25189436/3842050 ):

var socket = require('socket.io');
var express = require('express');
var http = require('http');

var app = express();
var server = http.createServer(app);

var io = socket.listen(server);

Then remove the app.use and app.get as they are no longer needed for how this is going to be done. 然后删除app.useapp.get因为它们将不再需要这样做。 Then add server.listen(8000); 然后添加server.listen(8000); at the end of the server.js. 在server.js的末尾。 For dependencies, use: <script src="//cdn.socket.io/socket.io-1.0.0.js"></script> . 对于依赖性,请使用: <script src="//cdn.socket.io/socket.io-1.0.0.js"></script> Then, to run your server, go to it in terminal and type node server.js . 然后,要运行您的服务器,请在终端上转到该服务器,然后键入node server.js Then just connect to it with your client. 然后只需与您的客户端连接即可。 Also, for events, in the server, use: 另外,对于事件,在服务器中,请使用:

io.on('connection', function (client) {
    client.on('someEvent', function(someVariables){
        //Do something with someVariables when the client emits 'someEvent'
        io.emit('anEventToClients', someData);
    });
    client.on('anotherEvent', function(someMoreVariables){
        //Do more things with someMoreVariables when the client emits 'anotherEvent'
        io.emit('anotherEventToClients', someMoreData);
    });
});

And in your client code: 在您的客户代码中:

socket.emit('someEvent', variables);
socket.on('anEventToClients', function(something){
    //Code when anEventToClient is emitted from the server
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM