Skip to content

Instantly share code, notes, and snippets.

@lilac
Last active January 22, 2018 12:50
Show Gist options
  • Save lilac/6c83331d659152ef62c7c6f10dd7cddd to your computer and use it in GitHub Desktop.
Save lilac/6c83331d659152ef62c7c6f10dd7cddd to your computer and use it in GitHub Desktop.
登顶大会新方案消息设计

玩家的回答

{
  "type": "answer",
  "payload": {
    "$question_id": "A" // 问题id -> 选项
  }
}

统计回答结果

{
  "type": "answer_stat",
  "payload": {
	"index": 1   // 问题索引序号
	"answer": "A" // 正常答案
	"timestamp": 1153636346
	"options": {	// 各个答案选项的统计数据
		"A": 2323,    // 选项A的统计
		"B": 10	// 选项B的统计
	}
  }
}

消息处理

因为WebSocket继承EventEmitter,消息可以转成事件,方便处理。如下面代码所示。

登录鉴权

jwt token包含openid和game_id。

WS登录

可参考文档http://iostreamer.me/ws/node.js/jwt/2016/05/08/websockets_authentication.html

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({port: 8080});
var jwt = require('jsonwebtoken');
/**
The way I like to work with 'ws' is to convert everything to an event if possible.
**/
function toEvent (message) {
try {
var event = JSON.parse(message);
this.emit(event.type, event.payload);
} catch(err) {
console.log('not an event' , err);
}
}
wss.on('connection', function(ws) {
ws.on('message', toEvent)
.on('authenticate', function (data) {
jwt.verify(data.token, options, function (err, decoded) {
//now is authenticated
});
});
ws.send('something');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment