Node + websocket real-time chat instance tutorial

Source: Internet
Author: User

Node + websocket real-time chat instance tutorial

Recently, the game owner needs a chat function. Because it is a real-time chat, he thought of the popular websocket. After one day and one night, he finally got a little eye-catching and summarized as follows:

Websocket is an html5 communication protocol that can communicate in real time. In this example, the chat is implemented using the socket. io framework. socket. io integrates multiple communication methods, such as websocket and xhr-polling.
1. Build a node Environment
On the node official website, I chose one-click installation of Windows msi. After installing node, You need to configure the PATH attribute of the system environment variable to add your test address PATH. biu ~ Biu ~

2. Install socket. io
Use the npm install-g socket. io command or download the file from the socket. io official website and put it in the node_modules folder.

 

3. server code server. js

/* Modules Introduction */var express = require ('express '), SiO2 = require ('socket. io '), fs = require ('fs'), path = require ('path') url = require ('url '); // ============================ app configuration ============== ==========================/*** app configuration */var app = module. export = express. createServer (); // ========================= configure socket. io ========================================//*** configure the socket. io **/var io = sio. listen (app); // assuming io is the Socket. IO server Objectio. configure (function () {// io. set ("transports", ["websocket"]) ;}); // =============================== socket link listener ====================== =/*** start socket link listening * @ param {Object} socket */io. sockets. on ('connection', function (socket) {// Public Information socket. on ('Public message', function (msg, fn) {socket. broadcast. emit ('Public message', msg); fn (true) ;}); // dropped, disconnected to process socket. on ('disconnect', function () {socket. broadcast. emit ('Public me Ssage ',' </pre> <span style = "color: red;"> disconnect... </Span> <pre class = "javascript"> ') ;}); app. listen (3000, function () {var addr = app. address (); console. log ('app listening on http: // 127.0.0.1: '+ addr. port );});

4. client code chat.html

<! -- <Script src = "/js/jquery. js "> </script> <script src ="/js/socket. js "> </script> --> <script type =" text/javascript "> // <! [CDATA [$ (function () {var socket = io. connect ('HTTP: // localhost: 100'); // start to connect to the server socket. on ('connect ', function () {$ (' # ing '). fadeOut (); show ('server connected successfully')}); // receives public messagesocket. on ('Public message', function (msg) {show (msg) ;}); $ ('# btn '). click (function () {var msg = $ ('# content '). val (); // send public message public messagesocket. emit ('Public message', msg, function (OK) {if (OK) {show (msg) ;}}) ;}); function show (msg) {var htm = "<div class = 'message'>" + msg + "</div>"; $ ('# main '). append (htm);} //]> </script> </pre> <div id = "main"> <div id = "connecting"> connecting to the server .. </div> & nbsp; </div> <div id = "send"> <input id = "content" type = "text"/> <button id = "btn"> send </button> </div>

5. Run the server command: node server. js.

For example, http: // localhost /... /Chat.html
The following are the results of Firefox and chrome.

Ps: currently, firebox does not support the websocket protocol. It uses xhr-polling and chrome uses the standard websocket protocol.
The image taken from the node server below

Currently, the websocket standards are not yet determined. Different browsers have different support for handshake protocols. In short, it is not recommended to use websocket now, biu ~ Biu ~

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.