如何使用socket.io来处理请求?

时间:2016-10-25 08:21:45

标签: html node.js socket.io httprequest

我正在尝试使用socket.io处理html页面和http服务器之间的请求无法POST / [HTTP / 1.1 404未找到1ms] 服务器代码:

<html>
  <head>
      <script src="https://cdn.socket.io/socket.io-1.3.4.js">
            var socket = io('http://localhost');
            console.log(socket);
            socket.emit('registration',"test");
      </script>

  </head>
  <body>

html页面如下

Parse error: syntax error, unexpected '.', expecting '&' or variable (T_VARIABLE) in /path/site/vendor/laravel/framework/src/Illuminate/Foundatio‌​n/helpers.php on line 475

1 个答案:

答案 0 :(得分:0)

  1. 安装节点,
  2. 为您的应用创建一个文件夹
  3. 创建package.json文件:

    { "name": "socket.io-test", "version": "0.0.1", "private": true, "scripts": { "start": "node server" }, "dependencies": { "express": "~4.13.1", "socket.io": "^1.4.6" } }

  4. 运行npm install

  5. 创建server.js - 粘贴在此处的原始代码:

    var express = require('express');
    var app = express();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    console.log(__dirname);
    app.use(express.static(__dirname+'/public'));
    app.get('/', function(req, res){
      res.sendfile(__dirname+'/public/registration.html');
    });
    io.on('connection', function(socket){
        socket.on('registration',function(msg){
        console.log('user data'+ msg);
      });
    });
    
    http.listen(3000, function(){
      console.log('listening on *:3000');
    });
    
  6. 在工作目录中创建/public文件夹

  7. 创建/public/registration.html文件:

    <html> <head> <script src='/socket.io/socket.io.js'></script> <script> var socket = io('http://localhost:3000'); socket.on('connect', function() { socket.emit('registration',"test"); document.getElementById('socket').innerHTML='connected'; }); </script> </head> <body> <h1>Testing socket.io with nodejs</h1> <h3 id="socket"></h3> </body> </html>

  8. 使用node servernpm start

  9. 启动服务器
  10. 转到浏览器中的localhost:3000
  11. 它会起作用