简体   繁体   English

为什么不通过socket.io发出事件触发

[英]Why doesn't emit event fire by socket.io

I'm using socket.io + express. 我正在使用socket.io + express。 I want to emit 'start' and 'user_info' event to server from client. 我想从客户端向服务器发出“开始”和“ user_info”事件。 But it doesn't work. 但这是行不通的。 I wrote like this... 我这样写...

server.js server.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");
        }
    });
});

I don't know why 'start' event is not being fired. 我不知道为什么未启动“开始”事件。 Do you have any idea? 你有什么主意吗?

You are missing the connection part of Socket.io 您缺少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});
   });

});

You may want to read the docs @ http://socket.io/ 您可能需要阅读文档@ http://socket.io/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM