├── component.json ├── package.json ├── README.md └── lib └── pomelo-client.js /component.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pomelo-jsclient-websocket", 3 | "description": "pomelo-jsclient-websocket", 4 | "keywords": [ 5 | "pomelo", 6 | "jsclient", 7 | "websocket" 8 | ], 9 | "version": "0.0.1", 10 | "main": "lib/pomelo-client.js", 11 | "scripts": [ 12 | "lib/pomelo-client.js" 13 | ], 14 | "repo": "https://github.com/pomelonode/pomelo-jsclient-websocket" 15 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pomelo-jsclient-websocket", 3 | "version": "0.1.1", 4 | "description": "pomelo jsclient for browser websocket", 5 | "main": "lib/pomelo-client.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/pomelonode/pomelo-jsclient-websocket" 9 | }, 10 | "keywords": [ 11 | "pomelo", 12 | "jsclient", 13 | "websocket" 14 | ], 15 | "author": "fantasyni", 16 | "license": "MIT" 17 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #Pomelo javascript websocket client 2 | 3 | The javascript websocket client library for [Pomelo](https://github.com/NetEase/pomelo). 4 | 5 | Since there are two kind connectors in pomelo 0.3, socket.io and socket(websocket), we provide two javascript clients for different usage. 6 | [websocket client](https://github.com/pomelonode/pomelo-jsclient-websocket) is optimized for data transfer size, the package is compressedin high rate. It's suitable for HTML5 online game, especially mobile platform. 7 | 8 | [socket.io client](https://github.com/pomelonode/pomelo-jsclient-socket.io) is excellent for browser compatibility, the package is in json. It's suitable for online realtime application on browser, like chat, on which browser compatiblity is an important issue. 9 | 10 | The apis are almost the same in both clients, except websocket client need a handshake callback for protocol data. 11 | Both clients use [component](https://github.com/component/component/) package manager for building. 12 | 13 | ##Usage 14 | 15 | ### connect to the server 16 | ``` javascript 17 | pomelo.init(params, callback); 18 | ``` 19 | params object are 20 | 21 | example: 22 | ``` javascript 23 | pomelo.init({ 24 | host: host, 25 | port: port, 26 | user: {}, 27 | handshakeCallback : function(){} 28 | }, function() { 29 | console.log('success'); 30 | }); 31 | ``` 32 | 33 | user field is user define json content 34 | handshakeCallback field is handshake callback function 35 | 36 | ### send request to server with callback 37 | ``` javascript 38 | pomelo.request(route, msg, callback); 39 | ``` 40 | 41 | example: 42 | ``` javascript 43 | pomelo.request(route, { 44 | rid: rid 45 | }, function(data) { 46 | console.log(dta); 47 | }); 48 | ``` 49 | 50 | ### send request to server without callback 51 | ``` javascript 52 | pomelo.notify(route, params); 53 | ``` 54 | 55 | ### receive message from server 56 | ``` javascript 57 | pomelo.on(route, callback); 58 | ``` 59 | 60 | example: 61 | ``` javascript 62 | pomelo.on('onChat', function(data) { 63 | addMessage(data.from, data.target, data.msg); 64 | $("#chatHistory").show(); 65 | }); 66 | ``` 67 | 68 | ### disconnect from server 69 | ``` javascript 70 | pomelo.disconnect(); 71 | ``` 72 | 73 | ##License 74 | (The MIT License) 75 | 76 | Copyright (c) 2012-2015 NetEase, Inc. and other contributors 77 | 78 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 79 | 80 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 81 | 82 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 83 | -------------------------------------------------------------------------------- /lib/pomelo-client.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | var JS_WS_CLIENT_TYPE = 'js-websocket'; 3 | var JS_WS_CLIENT_VERSION = '0.0.1'; 4 | 5 | var Protocol = window.Protocol; 6 | var protobuf = window.protobuf; 7 | var decodeIO_protobuf = window.decodeIO_protobuf; 8 | var decodeIO_encoder = null; 9 | var decodeIO_decoder = null; 10 | var Package = Protocol.Package; 11 | var Message = Protocol.Message; 12 | var EventEmitter = window.EventEmitter; 13 | var rsa = window.rsa; 14 | 15 | if(typeof(window) != "undefined" && typeof(sys) != 'undefined' && sys.localStorage) { 16 | window.localStorage = sys.localStorage; 17 | } 18 | 19 | var RES_OK = 200; 20 | var RES_FAIL = 500; 21 | var RES_OLD_CLIENT = 501; 22 | 23 | if (typeof Object.create !== 'function') { 24 | Object.create = function (o) { 25 | function F() {} 26 | F.prototype = o; 27 | return new F(); 28 | }; 29 | } 30 | 31 | var root = window; 32 | var pomelo = Object.create(EventEmitter.prototype); // object extend from object 33 | root.pomelo = pomelo; 34 | var socket = null; 35 | var reqId = 0; 36 | var callbacks = {}; 37 | var handlers = {}; 38 | //Map from request id to route 39 | var routeMap = {}; 40 | var dict = {}; // route string to code 41 | var abbrs = {}; // code to route string 42 | var serverProtos = {}; 43 | var clientProtos = {}; 44 | var protoVersion = 0; 45 | 46 | var heartbeatInterval = 0; 47 | var heartbeatTimeout = 0; 48 | var nextHeartbeatTimeout = 0; 49 | var gapThreshold = 100; // heartbeat gap threashold 50 | var heartbeatId = null; 51 | var heartbeatTimeoutId = null; 52 | var handshakeCallback = null; 53 | 54 | var decode = null; 55 | var encode = null; 56 | 57 | var reconnect = false; 58 | var reconncetTimer = null; 59 | var reconnectUrl = null; 60 | var reconnectAttempts = 0; 61 | var reconnectionDelay = 5000; 62 | var DEFAULT_MAX_RECONNECT_ATTEMPTS = 10; 63 | 64 | var useCrypto; 65 | 66 | var handshakeBuffer = { 67 | 'sys': { 68 | type: JS_WS_CLIENT_TYPE, 69 | version: JS_WS_CLIENT_VERSION, 70 | rsa: {} 71 | }, 72 | 'user': { 73 | } 74 | }; 75 | 76 | var initCallback = null; 77 | 78 | pomelo.init = function(params, cb) { 79 | initCallback = cb; 80 | var host = params.host; 81 | var port = params.port; 82 | 83 | encode = params.encode || defaultEncode; 84 | decode = params.decode || defaultDecode; 85 | 86 | var url = 'ws://' + host; 87 | if(port) { 88 | url += ':' + port; 89 | } 90 | 91 | handshakeBuffer.user = params.user; 92 | if(params.encrypt) { 93 | useCrypto = true; 94 | rsa.generate(1024, "10001"); 95 | var data = { 96 | rsa_n: rsa.n.toString(16), 97 | rsa_e: rsa.e 98 | } 99 | handshakeBuffer.sys.rsa = data; 100 | } 101 | handshakeCallback = params.handshakeCallback; 102 | connect(params, url, cb); 103 | }; 104 | 105 | var defaultDecode = pomelo.decode = function(data) { 106 | //probuff decode 107 | var msg = Message.decode(data); 108 | 109 | if(msg.id > 0){ 110 | msg.route = routeMap[msg.id]; 111 | delete routeMap[msg.id]; 112 | if(!msg.route){ 113 | return; 114 | } 115 | } 116 | 117 | msg.body = deCompose(msg); 118 | return msg; 119 | }; 120 | 121 | var defaultEncode = pomelo.encode = function(reqId, route, msg) { 122 | var type = reqId ? Message.TYPE_REQUEST : Message.TYPE_NOTIFY; 123 | 124 | //compress message by protobuf 125 | if(protobuf && clientProtos[route]) { 126 | msg = protobuf.encode(route, msg); 127 | } else if(decodeIO_encoder && decodeIO_encoder.lookup(route)) { 128 | var Builder = decodeIO_encoder.build(route); 129 | msg = new Builder(msg).encodeNB(); 130 | } else { 131 | msg = Protocol.strencode(JSON.stringify(msg)); 132 | } 133 | 134 | var compressRoute = 0; 135 | if(dict && dict[route]) { 136 | route = dict[route]; 137 | compressRoute = 1; 138 | } 139 | 140 | return Message.encode(reqId, type, compressRoute, route, msg); 141 | }; 142 | 143 | var connect = function(params, url, cb) { 144 | console.log('connect to ' + url); 145 | 146 | var params = params || {}; 147 | var maxReconnectAttempts = params.maxReconnectAttempts || DEFAULT_MAX_RECONNECT_ATTEMPTS; 148 | reconnectUrl = url; 149 | //Add protobuf version 150 | if(window.localStorage && window.localStorage.getItem('protos') && protoVersion === 0) { 151 | var protos = JSON.parse(window.localStorage.getItem('protos')); 152 | 153 | protoVersion = protos.version || 0; 154 | serverProtos = protos.server || {}; 155 | clientProtos = protos.client || {}; 156 | 157 | if(!!protobuf) { 158 | protobuf.init({encoderProtos: clientProtos, decoderProtos: serverProtos}); 159 | } 160 | if(!!decodeIO_protobuf) { 161 | decodeIO_encoder = decodeIO_protobuf.loadJson(clientProtos); 162 | decodeIO_decoder = decodeIO_protobuf.loadJson(serverProtos); 163 | } 164 | } 165 | //Set protoversion 166 | handshakeBuffer.sys.protoVersion = protoVersion; 167 | 168 | var onopen = function(event) { 169 | if(!!reconnect) { 170 | pomelo.emit('reconnect'); 171 | } 172 | reset(); 173 | var obj = Package.encode(Package.TYPE_HANDSHAKE, Protocol.strencode(JSON.stringify(handshakeBuffer))); 174 | send(obj); 175 | }; 176 | var onmessage = function(event) { 177 | processPackage(Package.decode(event.data), cb); 178 | // new package arrived, update the heartbeat timeout 179 | if(heartbeatTimeout) { 180 | nextHeartbeatTimeout = Date.now() + heartbeatTimeout; 181 | } 182 | }; 183 | var onerror = function(event) { 184 | pomelo.emit('io-error', event); 185 | console.error('socket error: ', event); 186 | }; 187 | var onclose = function(event) { 188 | pomelo.emit('close',event); 189 | pomelo.emit('disconnect', event); 190 | console.error('socket close: ', event); 191 | if(!!params.reconnect && reconnectAttempts < maxReconnectAttempts) { 192 | reconnect = true; 193 | reconnectAttempts++; 194 | reconncetTimer = setTimeout(function() { 195 | connect(params, reconnectUrl, cb); 196 | }, reconnectionDelay); 197 | reconnectionDelay *= 2; 198 | } 199 | }; 200 | socket = new WebSocket(url); 201 | socket.binaryType = 'arraybuffer'; 202 | socket.onopen = onopen; 203 | socket.onmessage = onmessage; 204 | socket.onerror = onerror; 205 | socket.onclose = onclose; 206 | }; 207 | 208 | pomelo.disconnect = function() { 209 | if(socket) { 210 | if(socket.disconnect) socket.disconnect(); 211 | if(socket.close) socket.close(); 212 | console.log('disconnect'); 213 | socket = null; 214 | } 215 | 216 | if(heartbeatId) { 217 | clearTimeout(heartbeatId); 218 | heartbeatId = null; 219 | } 220 | if(heartbeatTimeoutId) { 221 | clearTimeout(heartbeatTimeoutId); 222 | heartbeatTimeoutId = null; 223 | } 224 | }; 225 | 226 | var reset = function() { 227 | reconnect = false; 228 | reconnectionDelay = 1000 * 5; 229 | reconnectAttempts = 0; 230 | clearTimeout(reconncetTimer); 231 | }; 232 | 233 | pomelo.request = function(route, msg, cb) { 234 | if(arguments.length === 2 && typeof msg === 'function') { 235 | cb = msg; 236 | msg = {}; 237 | } else { 238 | msg = msg || {}; 239 | } 240 | route = route || msg.route; 241 | if(!route) { 242 | return; 243 | } 244 | 245 | reqId++; 246 | sendMessage(reqId, route, msg); 247 | 248 | callbacks[reqId] = cb; 249 | routeMap[reqId] = route; 250 | }; 251 | 252 | pomelo.notify = function(route, msg) { 253 | msg = msg || {}; 254 | sendMessage(0, route, msg); 255 | }; 256 | 257 | var sendMessage = function(reqId, route, msg) { 258 | if(useCrypto) { 259 | msg = JSON.stringify(msg); 260 | var sig = rsa.signString(msg, "sha256"); 261 | msg = JSON.parse(msg); 262 | msg['__crypto__'] = sig; 263 | } 264 | 265 | if(encode) { 266 | msg = encode(reqId, route, msg); 267 | } 268 | 269 | var packet = Package.encode(Package.TYPE_DATA, msg); 270 | send(packet); 271 | }; 272 | 273 | var send = function(packet) { 274 | if(socket) 275 | socket.send(packet.buffer); 276 | }; 277 | 278 | var handler = {}; 279 | 280 | var heartbeat = function(data) { 281 | if(!heartbeatInterval) { 282 | // no heartbeat 283 | return; 284 | } 285 | 286 | var obj = Package.encode(Package.TYPE_HEARTBEAT); 287 | if(heartbeatTimeoutId) { 288 | clearTimeout(heartbeatTimeoutId); 289 | heartbeatTimeoutId = null; 290 | } 291 | 292 | if(heartbeatId) { 293 | // already in a heartbeat interval 294 | return; 295 | } 296 | heartbeatId = setTimeout(function() { 297 | heartbeatId = null; 298 | send(obj); 299 | 300 | nextHeartbeatTimeout = Date.now() + heartbeatTimeout; 301 | heartbeatTimeoutId = setTimeout(heartbeatTimeoutCb, heartbeatTimeout); 302 | }, heartbeatInterval); 303 | }; 304 | 305 | var heartbeatTimeoutCb = function() { 306 | var gap = nextHeartbeatTimeout - Date.now(); 307 | if(gap > gapThreshold) { 308 | heartbeatTimeoutId = setTimeout(heartbeatTimeoutCb, gap); 309 | } else { 310 | console.error('server heartbeat timeout'); 311 | pomelo.emit('heartbeat timeout'); 312 | pomelo.disconnect(); 313 | } 314 | }; 315 | 316 | var handshake = function(data) { 317 | data = JSON.parse(Protocol.strdecode(data)); 318 | if(data.code === RES_OLD_CLIENT) { 319 | pomelo.emit('error', 'client version not fullfill'); 320 | return; 321 | } 322 | 323 | if(data.code !== RES_OK) { 324 | pomelo.emit('error', 'handshake fail'); 325 | return; 326 | } 327 | 328 | handshakeInit(data); 329 | 330 | var obj = Package.encode(Package.TYPE_HANDSHAKE_ACK); 331 | send(obj); 332 | if(initCallback) { 333 | initCallback(socket); 334 | } 335 | }; 336 | 337 | var onData = function(data) { 338 | var msg = data; 339 | if(decode) { 340 | msg = decode(msg); 341 | } 342 | processMessage(pomelo, msg); 343 | }; 344 | 345 | var onKick = function(data) { 346 | data = JSON.parse(Protocol.strdecode(data)); 347 | pomelo.emit('onKick', data); 348 | }; 349 | 350 | handlers[Package.TYPE_HANDSHAKE] = handshake; 351 | handlers[Package.TYPE_HEARTBEAT] = heartbeat; 352 | handlers[Package.TYPE_DATA] = onData; 353 | handlers[Package.TYPE_KICK] = onKick; 354 | 355 | var processPackage = function(msgs) { 356 | if(Array.isArray(msgs)) { 357 | for(var i=0; i