Presentation is loading. Please wait.

Presentation is loading. Please wait.

Web Socket Server (using node.js)

Similar presentations


Presentation on theme: "Web Socket Server (using node.js)"— Presentation transcript:

1 Web Socket Server (using node.js)

2 Web Socket Server Often, an HTTP server is used to detect WebSocket handshakes. WebSocket server can be built using many programming languages: Javascript: Socket.io Node.js Ruby: EventMachine Faye Python: pyWebSocket Tornado C++: uWebSockets C#: Fleck Java: Jetty .NET: SuperWebSocket Go: Gorilla

3 Web Socket Server Required Steps to Create a Web Socket Server in Node.JS Create instance of an http server and listen to a specific port Create a web socket server Listen for connections Callback for connections

4 Create HTTP server and listen
var http = require('http'); var server = http.createServer(function(request, response) { }); server.listen(1234, function() { console.log((new Date()) + ' Server is listening on port 1234');

5 Create Web Socket Server
var WebSocketServer = require('websocket').server; wsServer = new WebSocketServer({ httpServer: server }); wsServer.on('request', function(r){ // Code here to run on connection

6 Web Socket Server Methods
mount(serverConfig): Attach the WebSocketServer instance to a Node http.Server instance. unmount(): Detach the WebSocketServer instance from the Node http.Server. All existing connections are left alone and will not be affected, but no new WebSocket connections will be accepted. closeAllConnections():close all open WebSocket connections. shutDown():closes all open WebSocket connections and unmounts the server from the Node http.Server instance.

7 Web Socket Server Events request, function(webSocketRequest)
If autoAcceptConnections is set to false, a request event will be emitted by the server whenever a new WebSocket request is made. connect, function(webSocketConnection) Emitted whenever a new WebSocket connection is accepted. close, function(webSocketConnection, closeReason, description) Whenever a connection is closed for any reason, the WebSocketServer instance will emit a close event, passing a reference to the WebSocketConnection instance that was closed.

8 WebSocketRequest Properties
host: A string containing the contents of the Host header passed by the client. This will include the port number if a non-standard port is used. :3000 resource : A string containing the path that was requested by the client. resourceURL : A Node URL object containing the parsed resource, including the query string parameters. remoteAddress: The remote client's IP Address as a string. requestedProtocols : An array containing a list of strings that indicate the subprotocols the client would like to speak.

9 WebSocket Request Methods accept(acceptedProtocol, allowedOrigin)
Returns: WebSocketConnection instance call this function on the request object to accept the connection. If you don't have a particular subprotocol you wish to speak, you may pass null for the acceptedProtocol parameter. acceptedProtocol parameter is case-insensitive, and you must either pass a value that was originally requested by the client or null. The return value can be used to communicate with the connected client. reject([httpStatus], [reason]) If you decide to reject the connection, you must call reject. You may optionally pass an HTTP Status code (such as 404) and a textual description.

10 WebSocketRequest Events
requestAccepted , function(webSocketConnection) Emitted by the WebSocketRequest object when the accept method has been called and the connection has been established. webSocketConnection is the established WebSocketConnection instance that can be used to communicate with the connected client. requestRejected, function() Emitted by the WebSocketRequest object when the reject method has been called and the connection has been terminated.

11 Accepting Connection Accepting a connection Store connected clients
Listen for incoming messages Listen for a client disconnecting var count = 0; var clients = {}; var connection = r.accept(null, r.origin);

12 Accepting Connection Accepting a connection Store connected clients
Listen for incoming messages Listen for a client disconnecting var count = 0; var clients = {}; var connection = r.accept('echo-protocol', r.origin); clients[count++] = connection console.log((new Date()) + ' Connection accepted');

13 WebSocket Connection Properties
closeDescription: After the connection is closed, contains a textual description of the reason. closeReasonCode: After the connection is closed, contains the numeric close reason status code protocol: The subprotocol that was chosen to be spoken on this connection. This field will have been converted to lower case. remoteAddress: The IP address of the remote peer as a string. connected: A boolean value indicating whether or not the connection is still connected.

14 WebSocket Connection Methods
close([reasonCode], [description]): close the connection. drop([reasonCode], [description]): immediately close the socket without waiting for a response. sendUTF(string): Immediately sends the specified string as a UTF-8 WebSocket message to the remote peer. sendBytes(buffer): Immediately sends the specified Buffer object as a Binary WebSocket message to the remote peer. send(data): auto-detect the data type and send the appropriate message. If data is a Node Buffer, a binary message will be sent. Otherwise, the object provided must implement the toString() method.

15 WebSocket Connection Events message , function(message)
Emitted whenever a complete message is received. utf8Data binaryData close, function(reasonCode, description) This event is emitted when the connection has been fully closed. error, function(error) This event is emitted when there has been a socket error.

16 Listen for incoming messages
connection.on('message', function(message) { var msgString = message.utf8Data; for(var i in clients){ clients[i].sendUTF(msgString); } });

17 Listen for client disconnecting
connection.on('close', function(reasonCode, description) { delete clients[id]; console.log((new Date()) + connection.remoteAddress + ' isconnected.'); });

18 More Info


Download ppt "Web Socket Server (using node.js)"

Similar presentations


Ads by Google