在socket.io中发送接收数据

时间:2014-07-28 15:40:19

标签: html5 node.js sockets websocket socket.io

我是socket.io的新手并尝试复制http://socket.io/get-started/chat/

中给出的示例
    <!doctype html>
    <html>
      <head>
        <title>Socket.IO chat</title>
        <style>
          * { margin: 0; padding: 0; box-sizing: border-box; }
          body { font: 13px Helvetica, Arial; }
          form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
          form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
          form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
          #messages { list-style-type: none; margin: 0; padding: 0; }
          #messages li { padding: 5px 10px; }
          #messages li:nth-child(odd) { background: #eee; }
        </style>

        <script src="/socket.io/socket.io.js"></script>
        <script src="http://code.jquery.com/jquery.js"></script>
        <script>
          var socket = io();
          $('form').submit(function(){
            socket.emit('chat message', $('#m').val());
            $('#m').val('');
            return false;
          });
        </script>
      </head>
      <body>
        <ul id="messages"></ul>
        <form action="">
          <input id="m" autocomplete="off" /><button>Send</button>
        </form>
      </body>
    </html>

    var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    app.get('/', function(req, res){
      res.sendfile('index.html');
    });
    io.on('connection', function(socket){
       console.log('message pinged--------------');
       socket.on('chat message', function(msg){
        console.log('chat message ' + msg);
      });
      socket.on('message', function(obj){
        console.log("meg from server");
      });

    });

    http.listen(8079, function(){
      console.log('listening on *:8079');
    });
    console.log('Server is running...dnt worry!!');

    {
      "name": "socket-chat-example",
      "version": "0.0.1",
      "description": "my first socket.io app",
      "dependencies": {
        "express": "4.3.1",
        "socket.io": "1.0.2"
      }
    }

消息没有给...       socket.on('chat message',function(msg){             console.log('chat message'+ msg);           });

虽然我能够知道消息被ping的时间,但不知道是什么被打了

1 个答案:

答案 0 :(得分:1)

它没有按预期工作,因为您将submit处理程序添加到不存在的表单中。在您的脚本执行 之后, 正在创建表单。

要解决此问题,您应该将js代码包装在document-ready函数中:

$(function() {
  var socket = io();
  $('form').submit(function(){
    socket.emit('chat message', $('#m').val());
    $('#m').val('');
    return false;
  });
});

或将您的js代码放在body代码的最后。