WebSocket Server 3

Source: Internet
Author: User
In fact, the choice of the server is very broad, basically, the mainstream language has WebSocket server-side implementation, and we as the front-end development engineer, of course, to choose the more fiery Nodejs as our server-side environment.
Nodejs itself does not have native websocket support, but there is a third party implementation (if you are interested, you can refer to the WebSocket protocol to do their own implementation), we chose "WS" As our server-side implementation.
As the focus of this article is to explain WebSocket, so, for Nodejs do not do too much introduction, not too familiar friends can refer to Nodejs Guide (http://www.nodebeginner.org/index-zh-cn.html).
After installing the Nodejs, we need to install "WS", that is, our WebSocket implementation, the installation method is very simple, in the terminal or command line input:
NPM Install WS
, wait for the installation to complete.
Next, we need to start our websocket service. First of all, we need to build our own HTTP server, to build a simple HTTP server in Nodejs is very simple, so easy. The code is as follows:
var app = Http.createserver (onrequest). Listen (8888);
ONrequest () acts as a callback function that processes the request and then responds by finding the appropriate resource on the server based on the received URL and eventually returning it to the browser.
After the HTTP server has been built, we need to start the WebSocket service with the following code:
var websocketserver = require (' ws '). Server;
var wss = new Websocketserver ({Server:app});


As you can see from the code, it is good to have the HTTP instance we just built be passed in when initializing the WebSocket service. Here, our service-side code is almost ready to be written. What do you think? It's simple.

WebSocket Server 3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.