Server part:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
var WebSocketServer = require('websocket').server; var http = require('http'); var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(8080, function() { console.log((new Date()) + ' Server is listening on port 8080'); }); wsServer = new WebSocketServer({ httpServer: server, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection // facilities built into the protocol and the browser. You should // *always* verify the connection's origin and decide whether or not // to accept it. autoAcceptConnections: false }); function originIsAllowed(origin) { // put logic here to detect whether the specified origin is allowed. return true; } var connections = {}; var connectionIDCounter = 0; wsServer.on('request', function(request) { if (!originIsAllowed(request.origin)) { // Make sure we only accept requests from an allowed origin request.reject(); console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); return; } //var connection = request.accept('kraken-protocol', request.origin); var connection = request.accept(null, request.origin); connection.id = connectionIDCounter ++; connections[connection.id] = connection; console.log((new Date()) + ' Connection ID ' + connection.id + ' accepted.'); connection.on('message', function(message) { if (message.type === 'utf8') { console.log('Received Message: ' + message.utf8Data); //connection.sendUTF(message.utf8Data); broadcast(message.utf8Data) } else if (message.type === 'binary') { console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); connection.sendBytes(message.binaryData); } }); connection.on('close', function(reasonCode, description) { console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected. '+"Connection ID: " + connection.id); // Make sure to remove closed connections from the global pool delete connections[connection.id]; }); }); // Broadcast to all open connections function broadcast(data) { Object.keys(connections).forEach(function(key) { var connection = connections[key]; if (connection.connected) { connection.send(data); } }); } // Send a message to a connection by its connectionID function sendToConnectionId(connectionID, data) { var connection = connections[connectionID]; if (connection && connection.connected) { connection.send(data); } } |
- First, you need to have nodejs installed.
- Save the above code into websock-server\index.js
- Then, in your terminal/cmd, type npm install websocket@1.0.3 to install the nodejs websocket library.
- Make sure your port 8080 is not occupied by other program as I am using port 8080 in this example.
- Next, in your terminal/cmd, cd into the folder and type node index.js
- It now do not take in a protocol
- Able to do broadcast by keeping a list of connected clients
- Modified on request and close request to support the clients tracking function
- Instead of parrot back the same msg, it is now broadcasting any sender’s msg to everyone. More like how a chat room behave
Client Part:
For the client part, I going to create 2 interface, one for sending and receiving chat msg (index.htm), another for receiving chat msg only (logger.htm).- You will need to change the Server IP in it into yours (ws://192.168.0.200:8080)
- The code is pretty simple, everything is self described.
- So now i can open the index.htm and type a msg, and it will appear on the space below the input box, as well as in logger.htm
- I can even put index.htm into phonegap (need to provide option for user to enter the Server IP) and it can serve as a ‘controller’ while logger.htm can be modified to be a ‘receiver’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<html lang="en"> <head> <title>Node Based Echo</title> <script src="js/jquery-1.6.2.min.js" type="text/javascript"></script> <script src="js/jquery.websocket-0.0.1.js" type="text/javascript"></script> <script src="js/jquery.json.min.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> // sends a message to the websocket server function sendToServer() { ws.send('say', '{ messageTextA: ' + $('#echoText').val() + ' }'); //ws.send('krakenmsgB', '{ messageTextB: ' + $('#echoText').val() + ' }'); } // set-up web socket var ws = $.websocket("ws://192.168.0.200:8080/", { open: function () { }, close: function () { alert('websocket has been closed'); }, events: { say: function (e) { $('#returnText').append(e.data + "<br/>"); }, } }); </script> <div> <div style="float: left; clear: left; padding-top: 2px;"> Your text: </div> <div style="float: left; padding-left: 20px;"> <input type="text" id="echoText" style="width: 150px;" required /> </div> <div style="clear: left;"> <input type="button" onclick="javascript:sendToServer();" value="Send" /> </div> <div id="returnText" style="clear: left; height: 200px; padding-top: 30px;"> </div> </div> </body> </html> |