node.js - socket.IO 【 require('socket.io').listen(80);】不解!找遍所有群也未解决,求高手解答!
PHPz
PHPz 2017-04-17 11:33:41
0
1
579

官网上有一个这样的示例(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服务!请知道的解答一下,谢谢

PHPz
PHPz

学习是最好的投资!

reply all(1)
左手右手慢动作

According to my understanding, an HTTP service is created, then accessed through the browser, and then the long link is established through the client's var socket = io('http://localhost');, and then the backend is triggered. To trigger the connection event.

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.

javascript// 这段代码直接来自 socket.io 的第一个例子:Using with Node http server

var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(80);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

After writing this code, the complete socket.io client/server process can be realized:

  1. The client accesses the server / and gets index.html;
  2. Call index.html in client io.connect('http://localhost/chat') to create a connection;
  3. The server receives the connection event of /chat channel and executes the code of chat.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 three Using with... usages to provide services.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template