Skip to content

Instantly share code, notes, and snippets.

@shimondoodkin
Created May 7, 2016 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shimondoodkin/fbc30fedf6981dd5369cab8302adcf59 to your computer and use it in GitHub Desktop.
Save shimondoodkin/fbc30fedf6981dd5369cab8302adcf59 to your computer and use it in GitHub Desktop.
encapsulating header protocol, to minimize use of JSON.parse, which is cpu inefficient
// encapsulating header protocol:
//
// FAQ:
//
// why it is useful?, answer: to minimize use of JSON.parse, which is cpu inefficient.
//
// where ware it was inteded to be used? answer: on a plain socket or a websocket, like sockjs.
//
// note: there is a similar "STOMP" protocol, which is simpler(not encapsulating).
//
// Description:
//
// it is a prefix then a seperator then the rest
// it is possible to have several values but the previous valus must not include the seperator
//
// example:
// action_name:value1
// action_name:value1:value2 - the rest of the data whatever data even seperator : many times :::
//
// it is an incapsulatin protocol, like main massege contains a submessage of any type or of same type
//
// example
// action1:value_for_action1:subaction2:data_for_subaction2
//
// basic chat lexicon i have invented
//
// joined:userid:name
// left:userid
// message:r:roomid:{user:12312,text:234234}
// message:u:userid:{user:12312,text:234234}
//simple partser implementation using split until limit of 2 elements:
//message= message:r:roomid:{user:12312,text:234234}
var arg=message.split(':',2) var action=arg[0]; var rest=arg[1];
if(action==='message')
{
//rest= r:roomid:{user:12312,text:234234}
var arg=rest.split(':',3) var target=arg[0];var id_of_target=arg[1]; var message_rest=arg[2];
if(target==='r') { // r= room, u = user
broadcast_to_room(id_of_target,"message:r:"+id_of_target+":"+message_rest);
}
else if(target==='u') {
send_to_user(id_of_target,"message:u:"+id_of_target+":"+message_rest);
}
else {
console.log('rejected message',message);
}
}
else {
console.log('rejected message',message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment