psocket.io

0.0.3 • Public • Published

psocket.io

Build Status NPM version Downloads

How to use

The following example attaches psocket.io to a plain Node.JS HTTP server listening on port 3000.

var server = require('http').createServer();
var io = require('psocket.io')(server);
io.on('connection', function(socket){
  socket.on('event', function(data){});
  socket.on('disconnect', function(){});
});
server.listen(3000);

Standalone

var io = require('psocket.io')();
io.on('connection', function(socket){});
io.listen(3000);

In conjunction with Express

Starting with 3.0, express applications have become request handler functions that you pass to http or http PServer instances. You need to pass the PServer to socket.io, and not the express application function.

var app = require('express')();
var server = require('http').createServer(app);
var io = require('psocket.io')(server);
io.on('connection', function(){ /* �� */ });
server.listen(3000);

In conjunction with Koa

Like Express.JS, Koa works by exposing an application as a request handler function, but only by calling the callback method.

var app = require('koa')();
var server = require('http').createServer(app.callback());
var io = require('psocket.io')(server);
io.on('connection', function(){ /* �� */ });
server.listen(3000);

API

PServer

Exposed by require('psocket.io').

PServer()

Creates a new PServer. Works with and without new:

var io = require('psocket.io')();
// or
var Server = require('psocket.io');
var io = new PServer();

PServer(opts:Object)

Optionally, the first or second argument (see below) of the PServer constructor can be an options object.

The following options are supported:

  • serveClient sets the value for PServer#serveClient()
  • path sets the value for PServer#path()
  • maxStreamCntPerSocket sets the value for PServer#maxStreamCntPerSocket
  • sequentialRecv sets the value for PServer#sequentialRecv

The same options passed to socket.io are always passed to the engine.io Server that gets created. See engine.io options as reference.

PServer(srv:http#Server, opts:Object)

Creates a new PServer and attaches it to the given srv. Optionally opts can be passed.

PServer(port:Number, opts:Object)

Binds socket.io to a new http.Server that listens on port.

PServer#serveClient(v:Boolean):PServer

If v is true the attached server (see PServer#attach) will serve the client files. Defaults to true.

This method has no effect after attach is called.

// pass a server and the `serveClient` option
var io = require('psocket.io')(http, { serveClient: false });
 
// or pass no server and then you can call the method
var io = require('psocket.io')();
io.serveClient(false);
io.attach(http);

If no arguments are supplied this method returns the current value.

PServer#path(v:String):PServer

Sets the path v under which engine.io and the static files will be served. Defaults to /socket.io.

If no arguments are supplied this method returns the current value.

PServer#adapter(v:Adapter):Server

Sets the adapter v. Defaults to an instance of the PAdapter that ships with psocket.io which is memory based. See psocket.io-adapter.

If no arguments are supplied this method returns the current value.

PServer#origins(v:String):PServer

Sets the allowed origins v. Defaults to any origins being allowed.

If no arguments are supplied this method returns the current value.

PServer#origins(v:Function):PServer

Sets the allowed origins as dynamic function. Function takes two arguments origin:String and callback(error, success), where success is a boolean value indicating whether origin is allowed or not.

Potential drawbacks:

  • in some situations, when it is not possible to determine origin it may have value of *
  • As this function will be executed for every request, it is advised to make this function work as fast as possible
  • If psocket.io is used together with Express, the CORS headers will be affected only for psocket.io requests. For Express can use cors

PServer#sockets:PNamespace

The default (/) namespace.

PServer#attach(srv:http#Server, opts:Object):PServer

Attaches the PServer to an engine.io instance on srv with the supplied opts (optionally).

PServer#attach(port:Number, opts:Object):PServer

Attaches the PServer to an engine.io instance that is bound to port with the given opts (optionally).

PServer#listen

Synonym of PServer#attach.

PServer#onconnection(socket:engine#PSocket):PServer

Advanced use only. Creates a new psocket.io client from the incoming engine.io (or compatible API) psocket.

PServer#of(nsp:String):PNamespace

Initializes and retrieves the given PNamespace by its pathname identifier nsp.

If the namespace was already initialized it returns it right away.

PServer#emit

Emits an event to all connected clients. The following two are equivalent:

var io = require('psocket.io')();
io.sockets.emit('an event sent to all connected clients');
io.emit('an event sent to all connected clients');

For other available methods, see PNamespace below.

PServer#close

Closes socket server

var Server = require('socket.io');
var PORT   = 3030;
var server = require('http').Server();
 
var io = Server(PORT);
 
io.close(); // Close current server
 
server.listen(PORT); // PORT is free to use
 
io = Server(server);

PServer#use

See PNamespace#use below.

PNamespace

Represents a pool of sockets connected under a given scope identified by a pathname (eg: /chat).

By default the client always connects to /.

Events

  • connection / connect. Fired upon a connection.

    Parameters:

    • PSocket the incoming socket.

PNamespace#name:String

The namespace identifier property.

PNamespace#connected:Object

Hash of PSocket objects that are connected to this namespace indexed by id.

PNamespace#clients(fn:Function)

Gets a list of client IDs connected to this namespace (across all nodes if applicable).

An example to get all clients in a namespace:

var io = require('psocket.io')();
io.of('/chat').clients(function(error, clients){
  if (error) throw error;
  console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]
});

An example to get all clients in namespace's room:

var io = require('psocket.io')();
io.of('/chat').in('general').clients(function(error, clients){
  if (error) throw error;
  console.log(clients); // => [Anw2LatarvGVVXEIAAAD]
});

As with broadcasting, the default is all clients from the default namespace ('/'):

var io = require('psocket.io')();
io.clients(function(error, clients){
  if (error) throw error;
  console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB]
});

PNamespace#use(fn:Function):PNamespace

Registers a middleware, which is a function that gets executed for every incoming Socket and receives as parameter the socket and a function to optionally defer execution to the next registered middleware.

var io = require('psocket.io')();
io.use(function(socket, next){
  if (socket.request.headers.cookie) return next();
  next(new Error('Authentication error'));
});

Errors passed to middleware callbacks are sent as special error packets to clients.

PSocket

A PSocket is the fundamental class for interacting with browser clients. A PSocket belongs to a certain PNamespace (by default /) and uses an underlying Sockets to communicate.

PSocket#rooms:Array

A list of strings identifying the rooms this socket is in.

PSocket#sockets:Array

A list of the underlying Sockets.

PSocket#uuid:String

A unique identifier for the socket session.

PSocket#emit(name:String[, ��]):PSocket

Emits an event to the socket identified by the string name. Any other parameters can be included.

All datastructures are supported, including Buffer. JavaScript functions can't be serialized/deserialized.

var io = require('psocket.io')();
io.on('connection', function(socket){
  socket.emit('an event', { some: 'data' });
});

PSocket#join(name:String[, fn:Function]):PSocket

Adds the socket to the room, and fires optionally a callback fn with err signature (if any).

The socket is automatically a member of a room identified with its session id (see PSocket#uuid).

The mechanics of joining rooms are handled by the PAdapter that has been configured (see PServer#adapter above), defaulting to psocket.io-adapter.

PSocket#leave(name:String[, fn:Function]):PSocket

Removes the socket from room, and fires optionally a callback fn with err signature (if any).

Rooms are left automatically upon disconnection.

The mechanics of leaving rooms are handled by the PAdapter that has been configured (see PServer#adapter above), defaulting to psocket.io-adapter.

PSocket#to(room:String):PSocket

PSocket#in(room:String):PSocket

Sets a modifier for a subsequent event emission that the event will only be broadcasted to sockets that have joined the given room.

To emit to multiple rooms, you can call to several times.

var io = require('psocket.io')();
io.on('connection', function(socket){
  socket.to('others').emit('an event', { some: 'data' });
});

PSocket#compress(v:Boolean):PSocket

Sets a modifier for a subsequent event emission that the event data will only be compressed if the value is true. Defaults to true when you don't call the method.

var io = require('psocket.io')();
io.on('connection', function(socket){
  socket.compress(false).emit('an event', { some: 'data' });
});

Client

The Client class represents an incoming transport (engine.io) connection. A Client can be associated with many multiplexed Socket that belong to different Namespaces.

Client#conn

A reference to the underlying engine.io Socket connection.

Client#request

A getter proxy that returns the reference to the request that originated the engine.io connection. Useful for accessing request headers such as Cookie or User-Agent.

Debug / logging

Socket.IO is powered by debug. In order to see all the debug output, run your app with the environment variable DEBUG including the desired scope.

To see the output from all of Socket.IO's debugging scopes you can use:

DEBUG=socket.io* node myapp

License

MIT

Package Sidebar

Install

npm i psocket.io

Weekly Downloads

0

Version

0.0.3

License

MIT

Last publish

Collaborators

  • juhgiyo