ホームページ  >  に質問  >  本文

node.js - Socket.io一定要绑定http模块吗?我只想建立websocket服务

https://github.com/TooTallNat...

PHP中文网PHP中文网2713日前587

全員に返信(2)返信します

  • PHP中文网

    PHP中文网2017-04-17 14:53:19

    websocket是基于http协议的。

    返事
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 14:53:19

    好奇怪,为啥给的github地址是一个java-websocket的项目,问题却出现在了nodejs版块里面。。。我晕。 Anyway,我按照nodejs来说吧!现在是的!!!

    the back-end js:

    var express = require('express')
    var app = express();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    
    app.use(express.static(__dirname));
    app.get('/', function(req, res){
        res.sendFile(__dirname + '/index.html');
    });
    
    io.on('connection', function(socket){
        console.log('a user connected');
    });
    
    http.listen(8888, function() {
        console.log('listening on *:8888');
    });

    the front-end html file

    <html>
    <body>
      <!-- add ur js file here, it server as static content from ur back-end service(express static middleware)-->
      <!--<script src='/js/***.js'></script>-->
      <script src='/socket.io/socket.io.js'></script>
    </body>
    </html>
    
    • socket.io会自动捕捉到/socket.io的请求,然后返回客户端文件给你。

    返事
    0
  • キャンセル返事