首页 文章

在socket.io中发送接收数据

提问于
浏览
0

我是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"
      }
    }

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

虽然我能够知道消息何时被ping,但不知道什么是pinged

1 回答

  • 1

    它不能按预期工作,因为您将 submit 处理程序添加到不存在的表单 . 正在创建表单 after 您的脚本已执行 .

    要解决这个问题,你应该将你的js代码包装在document-ready函数中:

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

    或者将你的js代码放在 body 标签的最后 .

相关问题