Monthly Archives: August 2014

WebSocket Server & Mobile Client

Has been playing around on socket.io  but couldn’t get the client and server code separated. I need the server code running on a pc while the client code is just a static html that I can embed inside phonegap or etc. After hours of struggle, I decided to looks for other library and finally rest on these 2 combination: https://github.com/Worlize/WebSocket-Nodehttps://code.google.com/p/jquery-websocket/ thru Simon’s Hamsphire’s kraken blog Simon wrote a very good article on demonstrating these 2 combination. My article here  further demonstrate how to broadcast the msg to multiple clients and fixed some bugs. Ok, so lets’ do this step by step, server first then only the client.

Server part:

  1. First, you need to have nodejs installed.
  2. Save the above code into websock-server\index.js
  3. Then, in your terminal/cmd, type npm install websocket@1.0.3 to install the nodejs websocket library.
  4. Make sure your port 8080 is not occupied by other program as I am using port 8080 in this example.
  5. Next, in your terminal/cmd, cd into the folder and type node index.js
As you can see, I made some modification to the index.js file:
  • 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).
  1. You will need to change the Server IP in it into yours (ws://192.168.0.200:8080)
  2. The code is pretty simple, everything is self described.
  3. 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
  4. 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’
Index.html code   Finally, to save your day, I put up the full source code here at https://github.com/exiang/websock. All the best and have fun!