官网上有一个这样的示例(http://socket.io/docs/):
此处,说明是会创建一个http请求,但是我没明白,这个请求创建了之后,要怎么访问呢,我看代码engine.io.js里,有这样一段代码:
function listen(port, options, fn) {
if (‘function’ == typeof options) {
fn = options;
options = {};
}
var server = http.createServer(function (req, res) {
res.writeHead(501);
res.end('Not Implemented');
});
server.listen(port, fn);
// create engine server
var engine = exports.attach(server, options);
engine.httpServer = server;
return engine;
};
创建的一个501请求,但是这样创建的一个,用什么方法可以访问呢??
还有就是如果才能触发 connection事件呢??
一直没搞明白这两个问题
按我的理解是,创建了一个HTTP服务,然后通过浏览器去访问,然后再通过客户端的 var socket = io(‘http://localhost’);来建立长链接,然后触发后端的才能触发connection事件。
但是,最上面的代码,不清楚在哪个地方可以触发事件,并且怎么访问建立的HTTP服务!请知道的解答一下,谢谢
This understanding is wrong. The questioner probably thinks that the URL
/chat
can be accessed directly through the browser. This is wrong. This URL is just a channel of socket.io, not a real URL.The Socket.io example misses a very important part, that is, the following code. Its function is to return an html page, and the content of the page is the client's index.html.
After writing this code, the complete socket.io client/server process can be realized:
/
and getsindex.html
;index.html
in clientio.connect('http://localhost/chat')
to create a connection;/chat
channel and executes the code ofchat.on('connection')
.var io = require('socket.io').listen(80);
This code is a trap, and a * for beginners. In fact, when using socket.io, you don’t write it like this. Generally, you use one of the threeUsing with...
usages to provide services.