Wednesday, August 12, 2015

Websockets in node.js

In this post I'll show you how to start using websockets in node.js, the different types of modules there are, how to install them and use them to develop a simple example.

For those who don't know what websockets is about, here is a brief introduction:

Wikipedia says "WebSocket is a protocol providing full-duplex communications channels over a single TCP connection", this means that in a client-server communication the client as the server can send a message leaving behind the request-response protocol, where the exchange is always initiated by the client (usually a browser) and the server cannot send any data without the client requesting it first.

It also says "WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application", websockets was introduced in the clients or browsers since the html5 specification.

If you want to know more about websockets refer to the following links:
http://www.websocket.org/
http://en.wikipedia.org/wiki/WebSocket
https://developer.mozilla.org/en/docs/WebSockets

WS


Let's start with the first module "WS" , to start using it it needs to be installed so the following commands install the library:

To install the module to the current directory use the following command:
     $ npm install ws

To install the module in a global way use the following command:
    $ npm install ws -g

Once install it we can create an example using this module, the code below shows how to create a simple server with ws:


Save the file as ws_server.js, from the code you can see that the server will be running in port 8080, any request to this port the server will attend it. To create a client use the code below:


Save the file as ws_client.js and now lets run them, to run the server just type the following commands:

Server:
   $ node ws_server.js
   Msg received in server: Msg from client

Client:
   $ node ws_client.js
   Msg received in client: Msg from server

From the output you can see that the server starts and listens to any message when the client starts it also listens to messages and it sends a message, then the server receives it and answers this message

To find more about ws module go the following link https://github.com/einaros/ws  is the page of the library.

WebSocket


Lets try another module for websocket, the WebSocket-Node module, this module has more requirements, needs c++ and python to compile the native modules but they are optional but its efficiency decreases if they are not installed, if you are a windows user you will find harder to install.

To install WebSocket-Node module use the following command and use -g option to install it globally:

    $ npm install websocket -g

Once installed the module lets proceed to create the example:


Save the file as websocket_server.js. It creates a server for websockets that listens requests at the url ws://localhost:8080/example, in the code you can see that the port is configured at the instruction server.listen(8080), and the path is formed with request.accept('example', request.origin); .

Let's create a client for the server:


Save the file as websocket_client.js, from the code you can see that the client creates a connection to the server using the instruction client.connect('ws://localhost:8080/', 'example'); ,when a connection is done a message is sent to the server and the server should respond to the client with also a message.

Now lets run the scripts using the following commands:

Server:
   $ node websocket_server.js
   Received Message: Message from client

Client:
   $ node websocket_client.js
   Received: 'Msg from server'

The messages that the server and client are sending should be printed in the console if everything works as expected, if a problem happens with  the connection you should see a message like this "Connection Error: Error: connect ECONNREFUSED".

To find more about websocket module go the following link https://github.com/theturtle32/WebSocket-Node  is the page of the library.

engine.io


Another module to use for creating websockets is engine.io, although this module is part of a bigger framework you can still use this module to create websockets.

To install the module use the following command, to set it globally use the -g option:
    $ npm install engine.io -g

To create a client for this module the module "engine.io-client" is required, lets install the module:
    $ npm install engine.io-client

Lets create an example of a server:


Save the file as engineio_server.js, from the code you can see the configuration needed to run the server, it is pretty simple.

Now lets create a client for this server:


Save the file as engineio_client.js and lets run the example with the following commands:

Server:
        $ node engineio_server.js
         Msg Received at server:Msg from client

Client:
       $ node engineio_client.js
        Msg Received at client:Msg from server

As in the others examples if everything works as expected you should see the messages exchanged by the server and the client in console.

To find more about engine.io module go the following link https://github.com/socketio/engine.io  is the page of the library.

There are many other libraries that can be used to create websockets with nodejs, every one with its pros and cons but it would take another post to discuss this topic. I guess the hardest part would be to choose which library to use.

I wish this post helped you to better understand what websocket is and how to implement it in nodejs.



78 comments:

  1. I’m sincerely suggesting your blog to all my friends… I’ve changed myself in many thing after reading your blog… Thanks and keep going.
    J2EE Training in Chennai
    Java Training in Chennai
    Linux Training in Chennai

    ReplyDelete
  2. Thanks for this useful information about Nodejs. This article is really helpful for learning. Nodejs Training in Bangalore

    ReplyDelete
  3. Awesome blog. It was very informative. I would like to appreciate you. Keep updated like this best sap simple finance online training institute in hyderabad

    ReplyDelete
  4. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.
    python training in rajajinagar
    Python training in bangalore
    Python training in usa

    ReplyDelete
  5. Its really an Excellent post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog. Thanks for sharing....
    excel advanced excel training in bangalore
    Devops Training in Chennai

    ReplyDelete
  6. This is ansuperior writing service point that doesn't always sink in within the context of the classroom. In the first superior writing service paragraph you either hook the reader's interest or lose it. Of course your teacher, who's getting paid to teach you how to write an good essay, 

    Java training in Pune

    Java interview questions and answers

    Java training in Chennai | Java training institute in Chennai | Java course in Chennai

    Java training in Bangalore | Java training institute in Bangalore | Java course in Bangalore

    ReplyDelete
  7. Hello! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done an outstanding job.
    No.1 AWS Training in Chennai | Amazon Web Services Training Institute in Chennai
    AWS Online Training and Certification | Online AWS Certification Training Course

    ReplyDelete

  8. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you.
    Keep update more information..


    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training
    Selenium interview questions and answers

    ReplyDelete

  9. You need to kill time, you need entertainment. Refer to our website. hope you get the most comfort.travel trekking tips
    see the link Tent Camping 101 Exploring Smithriver



    ReplyDelete
  10. Looking for the best node.js company? Here is the list of best NodeJS developers that offer excellent Node JS development services.

    ReplyDelete
  11. Enjoyed reading the article above, really explains everything in detail, the article is very interesting and effective. Thank you and good luck for the upcoming articles learn Node JS training

    ReplyDelete
  12. This information really worth saying, thank you so much sharing valuable information with us
    Node JS Online training
    Node JS training in Hyderabad

    ReplyDelete
  13. I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.

    machine learning course

    artificial intelligence course in mumbai

    ReplyDelete
  14. Thanks for sharing blog. The explanation of your articles is very good. It was very interesting and meaningful. I really appreciate it! Keep updating stuffs like this.
    Machine Learning Training In Hyderabad

    ReplyDelete
  15. many business events particularly in specialized medical and academic fields charge sustainable registration fees it is hard to put a price on peer-to-peer networking. event marketing and team building invitation email sample

    ReplyDelete
  16. I think that you should definitely do it again sometime and hopefully I will be able to make it to that one
    Pakistani Drama Website

    ReplyDelete
  17. Hi - Amazing post thanks for sharing with me.
    mlm lead generation

    ReplyDelete
  18. Thanks for sharing such an interesting article. People should know this type of information to run in the flow and be present about what's going on in the market Digital Marketing Institute in KPHB

    ReplyDelete
  19. Just call QuickBooks customer service at Quickbooks Customer Service +1 877-693-1115 or talk to them live on their website.

    ReplyDelete
  20. Hivelance is the leading NFT marketplace development company offering best solutions in creating the classic opensea clone for your business. Our professionals expertise in developing an utility based platform for our valuable customers. We adopt blockchain technology for your project development that supports various aspects. for details visit opensea clone script development company

    ReplyDelete
  21. We Hivelance, with 10+ years specialized professionals in blockchain technology, leverage lightning networks for your crypto-wallets, as wallets are the integral part of cryptocurrencies, mainly in the trading/exchange part.
    The lightning network transactions per second is approximately 1 millions transactions. Our blockchain professionals excel in designing lightning nodes that connect main blockchain networks and lightning systems efficiently without lag. For details visit Bitcoin Lightning network development Company

    ReplyDelete
  22. Nice Blog. If you are looking for accounting adviser QuickBooks Customer Service is best for it. you can reach us at +1 855-885-5111.

    ReplyDelete

  23. QuickBooks offers phone support in addition to online support for people who need help with their software. It provides phone support and email support, both of which are Quickbooks Customer Service +18666695068

    ReplyDelete
  24. .QuickBooks is the most recommended and widely used accounting software which helps you get your work done easily and efficiently. This software comes with a customer service team that is active 24/7, so you can get answers for any sort of Quickbooks Customer Service question. You can contact them by dialling+1 855-444-2233.

    ReplyDelete
  25. Awesome Blog! Thanks for sharing this post. It is an interesting post for everyone. When i read about this post then got more information. I like it.

    vitamin and supplement stores kent

    MK-677 For Sale UK

    cbd supplements near Kent

    ReplyDelete
  26. Thank you for this informative blog it Contains a valuable knowledge also check out this Best Hospital In Faridabad

    ReplyDelete
  27. This is an awesome post. Really very informative and creative contents. Visit my website to get best Information About Best IAS Coaching Institute in Thane.
    Best IAS Coaching Institute in Thane
    Top IAS Coaching Institute in Thane

    ReplyDelete
  28. What a wonderful blog keep doing this work it contains good information and it really helps me a lot also check out this Best Hemorrhoids Surgeon in Delhi NCR

    ReplyDelete
  29. This blog is looking good and contains good knowledge thank you for this post keep doing this work also check out this one Best Heart hospital in Faridabad

    ReplyDelete

  30. Emblix Academy is today known as the best Digital Marketing Academy in Hyderabad which provides the student with a holistic learning experience throughout the course. Social media plays a vital role in deciding the consumer behavior towards Companies.

    ReplyDelete
  31. Get Data Science Certification from top-ranked universities UTM, Malaysia, and IBM. We provide extensive training for the future-ready workforce.
    data science training in malaysia

    ReplyDelete
  32. Keep doing this work it contains some interesting topics I was looking for and helps me a lot also have a look on this Best Hemorrhoids Surgeon in Delhi NCR

    ReplyDelete
  33. Such a wonderful blog it contains some good knowledge and topics thank you for this informative post keep doing this work also check out this one Best Fertility Clinic In Faridabad

    ReplyDelete
  34. What a wonderful informative post it has everything and help me to learn new things keep doing this work also have a look on this Best Embryo Freezing Centre In Faridabad

    ReplyDelete
  35. Thanks for sharing such great piece of Information , please also visit Buying Used Cars in Dubai

    ReplyDelete
  36. Thank you for this important informative post this blog contains some interesting topics and help me a lot keep doing this work also check out this Best pancreatic Surgeon Delhi NCR

    ReplyDelete
  37. Thank you for this informative post it really helps me a lot keep doing this work also have a look on this Makeup academy in gurgaon

    ReplyDelete
  38. Hi.
    Thank you for sharing this information. This good blog this blog was gives good information about coding and it's concepts we learn new thing in this blog thank for sharing this blog with us.
    Here is sharing some LabVIEW information may be its helpful to you.
    LabVIEW Training

    ReplyDelete
  39. Thank you for this informative post it really help me to understand new things and contains some interesting topics keep doing this work also have a look on this Best cardiologist in Faridabad

    ReplyDelete
  40. Thank you for addressing this important topic. Different types of modules of WebSocket in Node.js are very useful and important. Looking forward to your next post.
    Get information about alecensa 150 mg price here.

    ReplyDelete
  41. What a wonderful blog it really helped me to understand new things it also contains some important topics to read keep doing this work also have a look at this Male Infertility Treatment In Faridabad thank you for this informative post.

    ReplyDelete
  42. Keep doing this work also have a look at this IVF doctor In Faridabad this blog contains some interesting topics and helped me a lot to understand new things, Thank you for this informative post.

    ReplyDelete
  43. The journalroots offers a wide range of content, including fascinating stories on vintage vehicles that have made a lasting impression on automotive history and in-depth evaluations of the newest types of cars.

    ReplyDelete
  44. This comment has been removed by the author.

    ReplyDelete
  45. Leading CRM Strategy agency
    dedicated to helping companies scale
    their CRM investment

    A CRM system is more than just software; it's a growth engine.
    We specialize in turning your CRM investment into a powerhouse for business expansion.
    Stop missing out on revenue-generating opportunities and start harnessing the full potential of your CRM.
    Boost your sales pipeline and revenue with our comprehensive,
    proven services in revenue marketing, strategic marketing, and marketing technology

    https://www.provenroi.com

    ReplyDelete
  46. Verdict: Buying Instant YouTube Views—Yay or Nay?
    While the allure of instant growth is hard to ignore, the disadvantages are substantial. The risks of channel penalties, diminished engagement metrics, and ethical qualms outweigh the benefits. At the end of the day, building a YouTube channel is akin to cultivating a garden. It requires patience, effort, and the wisdom to reject shortcuts in favor of sustainable, authentic growth.
    https://www.buyyoutubesubscribers.in/youtube-video-views/

    ReplyDelete
  47. Great post! I found your insights on [specific topic] really helpful. FIBC Jumbo Bags. Please keep it up. I’ve also written about this on my blog Aerolam, and I’d love to hear your thoughts. Keep up the excellent work!

    ReplyDelete
  48. This comment has been removed by the author.

    ReplyDelete
  49. A comprehensive platform created to improve and expedite social media management for both individuals and corporations is called a Social Media Marketing panel Users can access a range of tools and services to improve their social media presence from one central location.

    ReplyDelete
  50. Great suggestions to keeping current. I m 80 but am still into fashion so it s good to know when to retire certain item of clothing. Gone today for me, puffy vest, infinity scarves, long sweaters, long pendent necklaces.

    https://ibaasonline.com/collections/pakistani-lawn-suits

    ReplyDelete
  51. This blog does an amazing job of explaining things in a way that makes them easy to understand.
    Data science Courses in London

    ReplyDelete
  52. Node.js and websockets are a perfect match for real-time web applications. The examples in this post are a great resource for anyone looking to implement websocket functionality.
    Data science courses in france

    ReplyDelete
  53. This is an excellent post for anyone looking to get started with WebSockets in Node.js! It provides a comprehensive introduction to WebSocket concepts, clear examples with multiple libraries, and step-by-step instructions on setting up both servers and clients. Overall, this post serves as a valuable guide for developers interested in implementing WebSockets with Node.js. Great job!
    Data science Courses in Ireland

    ReplyDelete