|
|
@@ -1,6 +1,7 @@
|
|
|
//引用http和socket.io模块
|
|
|
var us = {}
|
|
|
-us.http = require('http'), socketio = require('socket.io');
|
|
|
+us.http = require('http');
|
|
|
+var socketio = require('socket.io');
|
|
|
us.app = us.http.createServer(function (req, res) {});
|
|
|
//服务开始监听
|
|
|
us.app.listen(888);
|
|
|
@@ -13,12 +14,14 @@ us.socketio = socketio.listen(us.app);
|
|
|
//webSocket协议握手成功
|
|
|
////'connection' 是socket.io 保留的.不能错,结果在变量socket中
|
|
|
us.socketio.sockets.on('connection', function (socket) {
|
|
|
- //socket.emit('sSayhello', { hi: 'Happy new year.' }); //sSayHello是自己定义的,客户端听取的时候要
|
|
|
- //指定同名的事件。'cSayhello'需要和客户端发送时定义的事件名相同。
|
|
|
+ //前端javascript使用socket.emit('msg', { msg: str }); //字符串msg是自己定义的,
|
|
|
+ //socket.on('msg',function (data) {}); 后端需要用msg接收前端发送来的消息。'msg'需要和客户端发送时定义的事件名相同。
|
|
|
socket.on('msg', function (data) {
|
|
|
- //console.log('Get a msg from client ...');
|
|
|
+ console.log('Get a msg from client ...');
|
|
|
//console.log(data);
|
|
|
- socket.broadcast.emit('user message', data);
|
|
|
+ //向客户端javascript发送广播,注意:这里广播消息为bcast,
|
|
|
+ //则前端javascript用socket.on('bcast', function (msg) {alert(msg); });接收消息
|
|
|
+ socket.broadcast.emit('bcast', data);
|
|
|
});
|
|
|
//console.log("WebSocket connect ok....");
|
|
|
})
|