|
@@ -1,14 +1,25 @@
|
|
|
//引用http和socket.io模块
|
|
//引用http和socket.io模块
|
|
|
var us = {}
|
|
var us = {}
|
|
|
|
|
+//包含http模块
|
|
|
us.http = require('http');
|
|
us.http = require('http');
|
|
|
|
|
+//包含socket.io模块
|
|
|
var socketio = require('socket.io');
|
|
var socketio = require('socket.io');
|
|
|
|
|
+//创建httpserver
|
|
|
us.app = us.http.createServer(function (req, res) {});
|
|
us.app = us.http.createServer(function (req, res) {});
|
|
|
-//服务开始监听
|
|
|
|
|
-us.app.listen(888);
|
|
|
|
|
|
|
+//开启888端口,服务开始监听
|
|
|
|
|
+//us.app.listen(888);
|
|
|
|
|
+const hostname="127.0.0.1";
|
|
|
|
|
+const port=888;
|
|
|
|
|
+us.app.listen(port, hostname);
|
|
|
|
|
+console.log(`Server running at http://${hostname}:${port}/`);
|
|
|
|
|
+//也可以采用下面的写法,但代码更多
|
|
|
|
|
+/*us.app.listen(port, hostname, function() {
|
|
|
|
|
+ console.log(`Server running at http://${hostname}:${port}/`);
|
|
|
|
|
+});*/
|
|
|
//输出调试信息
|
|
//输出调试信息
|
|
|
//console.log("Http Server start at 888");
|
|
//console.log("Http Server start at 888");
|
|
|
|
|
|
|
|
-//socketio开始监听
|
|
|
|
|
|
|
+//socketio开始监听http请求
|
|
|
us.socketio = socketio.listen(us.app);
|
|
us.socketio = socketio.listen(us.app);
|
|
|
|
|
|
|
|
//webSocket协议握手成功
|
|
//webSocket协议握手成功
|
|
@@ -20,7 +31,7 @@ us.socketio.sockets.on('connection', function (socket) {
|
|
|
console.log('Get a msg from client ...');
|
|
console.log('Get a msg from client ...');
|
|
|
//console.log(data);
|
|
//console.log(data);
|
|
|
//向客户端javascript发送广播,注意:这里广播消息为bcast,
|
|
//向客户端javascript发送广播,注意:这里广播消息为bcast,
|
|
|
- //则前端javascript用socket.on('bcast', function (msg) {alert(msg); });接收消息
|
|
|
|
|
|
|
+ //则前端javascript用socket.on('bcast', function (r) {alert(r); });接收消息
|
|
|
socket.broadcast.emit('bcast', data);
|
|
socket.broadcast.emit('bcast', data);
|
|
|
});
|
|
});
|
|
|
//console.log("WebSocket connect ok....");
|
|
//console.log("WebSocket connect ok....");
|