Socket.io没有从客户端或服务器发送?

时间:2015-11-28 14:40:25

标签: javascript node.js socket.io

在客户端,我有这段代码:

var serverAddress = "http://localhost:8081";
var socket = io(serverAddress);

socket.on('connect', function(){
    console.log("Connected to server on %s", serverAddress);
});
socket.emit("xxx", {text : "attack"});

在服务器上,我有这个:

var express = require('express');
var http = require('http');

var app = express();
var server = http.createServer(app);
var socket = require('socket.io').listen(server);

socket.on('connect', function() {
    console.log('A user is connected to server');
});
socket.on('xxx', function(data) {
    console.log(data);
});

connect事件被触发并在服务器上被捕获,但xxx事件甚至没有被触发也没有被捕获。怎么了? Console.log未报告任何错误。

1 个答案:

答案 0 :(得分:0)

您将socket.io 服务器与socket.io 连接混淆

当建立新的客户端连接时,服务器会收到connection事件。该事件的参数(通常称为socket)表示该连接。这是您需要用来收听消息的对象:

// server
...
var io = require('socket.io').listen(server);
...
io.on('connection', function(socket) {
  console.log('A user is connected to server');
  socket.on('xxx', function(data) {
    console.log(data);
  });
});