-
Notifications
You must be signed in to change notification settings - Fork 0
jQuery.socket is the feature-rich and flexible interface for two-way communication, just as if jQuery.ajax is the interface for Ajax interaction.
jQuery.socket()
Returns the first socket
jQuery.socket(url, [options])
Returns the socket object which is mapped to the given url, or if there is no mapped socket, creates a new socket with the given options, connects to the given url and returns it.
transports
An array of the transport ids, in order of index. The transport is used to establish a connection, send data and close the connection. The default is ["ws", "sse", "stream", "longpoll"]. For details, see Supported Transports and Browsers.
{transports: ["sse", "stream"]};timeout
A timeout value in milliseconds. The timeout timer starts at the time the connecting event is fired. If the timer expires before the connection is established, the close event is fired. The default is false, which means no timeout.
{timeout: 5000};heartbeat
A heartbeat interval value in milliseconds. A opened socket continuously sends a heartbeat event to the server each time the value has elapsed. Actually, the socket sends the event 5 seconds before the heartbeat timer expires to wait the server's echo. If the event echoes back within 5 seconds, the socket reset the timer. Otherwise, the close event is fired. For that reason, the value must be larger than 5000 and the recommended value is 20000. The default is false, which means no heartbeat.
{heartbeat: 20000};lastEventId
A initial value for the last event id to be passed to the urlBuilder function. The default is empty string.
{lastEventId: window.localStorage && window.localStorage["eventId"] || ""};credentials
If the value is true and the browser supports the Cross-Origin Resource Sharing specification, user credentials such as cookies and HTTP authentication is to be included in a cross-origin connection. The spec requires the server to add some response headers. This option affects the EventSource of sse transport and the XMLHttpRequest of stramxhr and longpollajax transport. The default is false
{credentials: true};sharing
A flag indicating that sharing socket across tabs and windows is enabled or not. As long as the cookie is enabled, the socket object will try to automatically share a real connection if there is no corresponding one, and find and use a shared connection if it exists within the cookie's scope. Windows don't need to have any parent window. By default, the value is set to true to save unnecessary network traffic. Set the value to false to disable.
{sharing: false};prepare(connect, cancel, options)
A function that is called before the socket tries to connect and determines whether to allow the socket to try to connect or not when a physical connection is needed. In other words, if the option sharing is true and there is an available shared socket, the function will not be executed. The function receives three arguments: The callback to connect, the callback to cancel and merged options object. You can use this when the opening handshake is needed, the user is needed to be authenticated and the option is needed to be managed by the server. The default function simply executes the connect function.
{
prepare: function(connect, cancel, options) {
$.ajax("/socket-prepare").done(function(data) {
options.id = data.id;
options.transports = data.transports;
options.timeout = data.timeout;
options.heartbeat = data.heartbeat;
connect();
})
.fail(function() {
cancel();
});
}
};reconnect(lastDelay, attempts)
A function to be used to schedule reconnection. The function is called every time after the close event is fired and should return a delay in milliseconds or false not to reconnect. The function receives two arguments: The last delay in milliseconds used or null at first and the total number of reconnection attempts. This can be disabled by setting the value to false. The default function returns 500 at first and then the double of the last delay of each call.
{
reconnect: function(lastDelay, attempts) {
return attempts > 10 ? false : 2 * (lastDelay || 250);
}
};idGenerator()
A function to be used to generate a socket id. The function should return a string and the returned string should be unique enough for the server to use it as a identifier of the connection until the connection disconnects. The default function generates a random UUID.
{
idGenerator: function() {
return Math.random().toFixed(20).substring(2);
}
};urlBuilder(url, params)
A function to be used to build a url to which to connect. The function should return a url including the given parameters. The function accepts two arguments: The absolute form of the given url and the params object containing socket information. The default function appends a query string representation of the params to the url.
{
urlBuilder: function(url, params) {
var part = params.id + "/" + params.transport + "/" + params.heartbeat + "/" + params.lastEventId;
return url.replace(/(\?)(.*)|$/, "/" + part + "$1$2"));
}
};params
An object for the second parameter to be passed to the urlBuilder function. This object is merged with the default one, overriding the default one's properties. The default params object has five properties: id, heartbeat, transport, lastEventId and _ which is the current timestamp to prevent caching.
{
params: {
id: "overriding the id parameter",
key: function() {
return "value";
}
}
};inbound(data)
A function to be used to convert data sent by the server into an event object. Every data sent by the server except binary invokes the function and it should return an event object having type. Binary data is considered as a message event instead. The event object can have the following optional properties: id(an event id), reply(if true then a reply event will be sent) and data(the first argument of corresponding handlers). The default function parses the data as JSON and returns the parsed value because the server sends a JSON string representing the event as data by default.
{
inbound: function(data) {
if (data === "h") {
return {type: "heartbeat"};
}
return $.parseJSON(data);
}
};outbound(event)
A function to be used to convert an event object into data to be sent to the server. Every data to be sent to the server except binary invokes the function and it should return a string. Binary data is sent as it is instead. The given event object has id(an event id), type(a event type which the user input), reply(if true then a reply event will be received), socket(a socket id) and data(data which the user input) properties. The default function serializes the event object into JSON and returns it because the server accepts a JSON string representing the event as data by default.
{
outbound: function(event) {
if (event.type === "heartbeat") {
return "h";
}
return $.stringifyJSON(event);
}
};xdrURL(url)
A function that can be used to modify a url to be used by the XDomainRequest. For security reasons, the XDomainRequest excludes cookies when sending a request, so a session state cannot be maintained. This problem can be solved by rewriting the url to contain session information. How to rewrite the url is depending on the server app. For details, see my Q&A on StackOverflow. If you wish to disable transports using XDomainRequest, which are streamxdr and longpollxdr, set the value to false. The default function modifies the url only if JSESSIONID or PHPSESSID cookie exists. For example, If the url is url?key=value and JSESSIONID cookie exists, the url becomes url;jsessionid=${cookie.JSESSIONID}?key=value, and if PHPSESSID cookie exists, the url becomes url?PHPSESSID=${cookie.PHPSESSID}&key=value. Otherwise, it returns false.
{
xdrURL: function(url) {
var match = /(?:^|;\s*)JSESSIONID=([^;]*)/.exec(document.cookie);
return match ? url.replace(/;jsessionid=[^\?]*|(\?)|$/, ";jsessionid=" + match[1] + "$1") : url;
}
};streamParser(chunk)
A function to parse stream response to find data from chunks. The function is called only if the transport is stream, receives chunks whose padding is striped and should return an array of data and the returned array's length varies with each chunk because a single chunk may contain a single data, multiple data or a fragment of a data. The default function parses a chunk according to the event stream format, but deals with the data field only.
{
streamParser: function(chunk) {
var data = chunk.split(";");
data[0] = (this.session("data") || "") + data[0];
this.session("data", data[data.length - 1]);
return data.slice(0, data.length - 1);
}
};option(key)
Finds the value of an option from the options merged with the default options and the given options. .option("id") returns the socket id and .option("url") returns the original url.
$.socket().option("url");session(key, [value])
Gets or sets the session-scoped value with the specified key. The session scope is reset every time the socket opens.
$.socket().session("url");state()
Determines the state of the socket. It can be in one of five states: preparing, connecting, opened, closed and waiting.
$.socket().state();on(event, handler)
Adds a given event handler for a given event. When the handler executes, the this keyword refers to the socket where the event occurred.
$.socket().on("message", function() {
this.session("counts", (this.session("counts") || 0) + 1);
});off(event, handler)
Removes a given event handler for a given event.
$.socket().off("notification", app.handleNotification);one(event, handler)
Adds a given one time event handler for a given event. A handler bound by one can be called only once in a socket life cycle. In other words, the handler will not be reset upon reconnection.
$.socket().one("message", function() {
alert("first message!");
});send([event], data, [callback])
Sends an event whose type is a given event or message if not provided and data is a given data to the server. If a callback is string, it is regarded as the callback event name and that event will be fired with data returned from the server, if a callback is function, it will be invoked with the data. Note that passing callback event name is much recommended than passing function because it is not compatible with sharing socket.
$.socket()
.send("data")
.send("event", {foo: "bar"})
.send("account.add", {username: "flowersinthesand"}, "account.added");
//.send("account.unique", "username", function(result) {
// alert("This username is " + (result ? "available" : "already taken"));
//});fire(event, [data])
Fires all event handlers attached to the local socket for the given event type.
$.socket()
.fire("init")
.fire("account.added", {username: "flowersinthesand", twitter: "flowersits"});broadcast(event, [data])
Broadcasts an event to session sockets which means a socket sharing its connection and sockets connecting to that connection.
$.socket()
.broadcast("ready")
.broadcast("notification", {type: "success", msg: "Well done!"});close()
Closes the socket.
$.socket().close();-
connecting(handler),open(handler),message(handler),close(handler), andwaiting(handler)
A shortcut for on(event, handler) method.