Web Socket Server using node js Web Socket
Web Socket Server (using node. js)
Web Socket Server • Often, an HTTP server is used to detect Web. Socket handshakes. • Web. Socket server can be built using many programming languages: • Javascript: • Socket. io • Node. js • Ruby: • Event. Machine • Faye • Python: • py. Web. Socket • Tornado • C++: • u. Web. Sockets • C#: • Fleck • Java: • Jetty • . NET: • Super. Web. Socket • Go: • Gorilla
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
Create HTTP server and listen var http = require('http'); var server = http. create. Server(function(request, response) { }); server. listen(1234, function() { console. log((new Date()) + ' Server is listening on port 1234'); });
Create Web Socket Server var Web. Socket. Server = require('websocket'). server; ws. Server = new Web. Socket. Server({ http. Server: server }); ws. Server. on('request', function(r){ // Code here to run on connection });
Web Socket Server Methods • mount(server. Config): Attach the Web. Socket. Server instance to a Node http. Server instance. • unmount(): Detach the Web. Socket. Server instance from the Node http. Server. All existing connections are left alone and will not be affected, but no new Web. Socket connections will be accepted. • close. All. Connections(): close all open Web. Socket connections. • shut. Down(): closes all open Web. Socket connections and unmounts the server from the Node http. Server instance.
Web Socket Server Events • request, function(web. Socket. Request) If auto. Accept. Connections is set to false, a request event will be emitted by the server whenever a new Web. Socket request is made. • connect, function(web. Socket. Connection) Emitted whenever a new Web. Socket connection is accepted. • close, function(web. Socket. Connection, close. Reason, description) Whenever a connection is closed for any reason, the Web. Socket. Server instance will emit a close event, passing a reference to the Web. Socket. Connection instance that was closed.
Web. Socket. Request 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. www. example. com: 8080 127. 0. 0. 1: 3000 • resource : A string containing the path that was requested by the client. • resource. URL : A Node URL object containing the parsed resource, including the query string parameters. • remote. Address: The remote client's IP Address as a string. • requested. Protocols : An array containing a list of strings that indicate the subprotocols the client would like to speak.
Web. Socket Request Methods • accept(accepted. Protocol, allowed. Origin) • Returns: Web. Socket. Connection 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 accepted. Protocol parameter. • accepted. Protocol 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([http. Status], [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.
Web. Socket. Request Events • request. Accepted , function(web. Socket. Connection) • Emitted by the Web. Socket. Request object when the accept method has been called and the connection has been established. web. Socket. Connection is the established Web. Socket. Connection instance that can be used to communicate with the connected client. • request. Rejected, function() Emitted by the Web. Socket. Request object when the reject method has been called and the connection has been terminated.
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);
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');
Web. Socket Connection Properties • close. Description: After the connection is closed, contains a textual description of the reason. • close. Reason. Code: 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. • remote. Address: The IP address of the remote peer as a string. • connected: A boolean value indicating whether or not the connection is still connected.
Web. Socket Connection Methods • close([reason. Code], [description]): close the connection. • drop([reason. Code], [description]): immediately close the socket without waiting for a response. • send. UTF(string): Immediately sends the specified string as a UTF-8 Web. Socket message to the remote peer. • send. Bytes(buffer): Immediately sends the specified Buffer object as a Binary Web. Socket 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 to. String() method.
Web. Socket Connection Events • message , function(message) • Emitted whenever a complete message is received. • utf 8 Data • binary. Data • close, function(reason. Code, 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.
Listen for incoming messages connection. on('message', function(message) { var msg. String = message. utf 8 Data; for(var i in clients){ clients[i]. send. UTF(msg. String); } });
Listen for client disconnecting connection. on('close', function(reason. Code, description) { delete clients[id]; console. log((new Date()) + connection. remote. Address + ' isconnected. '); });
More Info https: //github. com/theturtle 32/Web. Socket-Node
- Slides: 18