Skip to content

socket.io使用、canvas使用、nginx反向代理websocket #65

@zhan2016

Description

@zhan2016

问题描述

希望实现白板功能,实现多个用户之间实时的共享和操作同一张图像(操作功能主要是划线,标记等协作功能).

设定的解决方案

服务器端

使用express新建一个httpServer,将socket.io挂载到httpServer上,在connection事件里面绑定一系列socket.io事件(socket.io是基于websocket的封装).

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});
var currenimage = null;
io.on('connection',onConnection);

在有新人加入的时候,共享当前的图像给他(socket.emit仅仅给他!)

 if(currenimage != null)
    {
        console.log('a user connected');
        socket.emit('newImageAttached', currenimage);
    }

在有人切换图像的时候,给除他以外所有客户端发消息更新客户端图像

socket.on('newImageAttached',function(msg){
        currenimage = msg;
        socket.broadcast.emit('newImageAttached', msg);
        //console.log(msg);
    });

区分各种消息发送的范围:

socket.emit('message', "this is a test"); //sending to sender-client only
socket.broadcast.emit('message', "this is a test"); //sending to all clients except sender
socket.broadcast.to('game').emit('message', 'nice game'); //sending to all clients in 'game' room(channel) except sender
socket.to('game').emit('message', 'enjoy the game'); //sending to sender client, only if they are in 'game' room(channel)
socket.broadcast.to(socketid).emit('message', 'for your eyes only'); //sending to individual socketid
io.emit('message', "this is a test"); //sending to all clients, include sender
io.in('game').emit('message', 'cool game'); //sending to all clients in 'game' room(channel), include sender
io.of('myNamespace').emit('message', 'gg'); //sending to all clients in namespace 'myNamespace', include sender
socket.broadcast.emit(); //send to all connected clients except the one that sent the message
socket.on(); //event listener, can be called on client to execute on server
io.sockets.socket(); //for emiting to specific clients
io.sockets.emit(); //send to all connected clients
io.sockets.on() ; //initial connection from a client.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions