NodeJS+Expres+Socket.io实现HTTP通知websocket客户端

来源:互联网 发布:python和php哪个好学 编辑:程序博客网 时间:2024/05/17 01:16

无聊的时候乱想的,在游戏客户端中调用http接口,及时的通知web端消息。公司的一个需求,虽然因为浏览器的兼容性,放弃了这个方案。下面是个乱写的demo

var app = require('express')();var http = require('http').Server(app);var io = require('socket.io')(http);var events = require('events');var emitter = new events.EventEmitter();var id = null;app.get('/', function(req, res){    res.send('<h1>Welcome Realtime Server</h1>');});//接受app.get("/receiveMessage", function(req, res) {    emitter.emit("webreceive", {id:10});    res.send("i can play");});io.on('connection', function(socket){    if(id == null) {        id = socket.id;    };    //只发给当前客户端    socket.emit("hello", "socket:" + socket.id);    //发送给所有连接的客户端    io.emit("hello", "io:" + socket.id);    socket.on("disconnect", function() {        console.log("a user go out");    });    socket.on("message", function(obj) {        io.emit("message", obj);    });    emitter.on("webreceive", function(obj) {        if(socket.id == id) {            socket.emit("message", obj);            console.log("i'm webreceive");        }    })});http.listen(3000, function(){    console.log('listening on *:3000');});

receiveMessage负责接收通知,然后通知所有的客户端。里面的id是乱写的,可以定义一个对应关系。到这里,作业就完成了。

0 0
原创粉丝点击