On client side, I have this code:
在客户端,我有这个代码:
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"});
And on server, I have this one:
在服务器上,我有这个:
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
event is fired and caught on server, but xxx
event isn't even fired nor caught. What's wrong? Console.log
didn't report any error.
连接事件被触发并在服务器上捕获,但xxx事件甚至没有被触发也没有被捕获。怎么了? Console.log没有报告任何错误。
1 个解决方案
#1
0
You're confusing the socket.io server with a socket.io connection.
您将socket.io服务器与socket.io连接混淆。
The server receives a connection
event when a new client connection is made. The argument for that event (usually called socket
) represents that connection. This is the object that you need to use to listen to messages:
当建立新的客户端连接时,服务器接收连接事件。该事件的参数(通常称为套接字)表示该连接。这是您需要用来侦听消息的对象:
// 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);
});
});
#1
0
You're confusing the socket.io server with a socket.io connection.
您将socket.io服务器与socket.io连接混淆。
The server receives a connection
event when a new client connection is made. The argument for that event (usually called socket
) represents that connection. This is the object that you need to use to listen to messages:
当建立新的客户端连接时,服务器接收连接事件。该事件的参数(通常称为套接字)表示该连接。这是您需要用来侦听消息的对象:
// 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);
});
});