0

我正在使用 socket.io + express。我想从客户端向服务器发出 'start' 和 'user_info' 事件。但它不起作用。我是这样写的...

服务器.js

var express = require("express");
var http = require("http");
var socket = require("socket.io");
var app = express();
var ejs = require("ejs");
var server = http.createServer(app);
var io = require("socket.io").listen(server);
var redis = require("redis");
var _ = require("underscore");
require("./models/User");

app.get("/",function(req,res){

  res.render("index",{});

});

  
  socket.on("start",function(data){
    console.log("Started");
  });

   socket.on("user_info",function(user_info){
    var self = this;
        var name = user_info.name;
        var password = user_info.password;
    user.name = name;
    user.password = password;
    var data = JSON.stringify({name: name,password: password});
  });



### client.js


$(document).ready(function(){
    var socket = io.connect("http://localhost:8080");

  
 

    $("#register-btn").on("click",function(data){
        $("#notice").html("Registerd");
        var name = $("#name").val();
        var password = $("#password").val();
        var confirmPassword = $("#confirm-password").val();

        if (name && (password === confirmPassword)){
                    // user_info event is works.
            socket.emit("user_info",{"name": name,"password": password});
                    // I wonder why  start event does not works.
                    socket.emit("start",{"name": "yahoo"});

        }else{
            $("#notice").html("try again");
        }
    });
});

我不知道为什么没有触发“开始”事件。你有什么主意吗?

4

1 回答 1

1

您缺少 Socket.io 的连接部分

// Noticed I removed the var socket = require('....
var io = require("socket.io").listen(server);

io.sockets.on('connection', function (socket) {

   console.log('Client Connected')       

   socket.on("start",function(data){
      console.log("Started");
   });

   socket.on("user_info",function(user_info){
      var self = this;
      var name = user_info.name;
      var password = user_info.password;
      user.name = name;
      user.password = password;
      var data = JSON.stringify({name: name,password: password});
   });

});

您可能想阅读文档@ http://socket.io/

于 2012-08-03T06:24:04.573 回答