Node+websocket Real-time Chat example tutorial

Source: Internet
Author: User
Tags emit require socket install node node server

Recently, responsible for the game needs a chat function, because it is real-time chat, then think of the websocket, toss a day and night, finally a bit, now summed up as follows:

WebSocket is a HTML5 communication protocol that can communicate in real time. In this case, the chat is implemented using the framework Socket.io of the socket, Socket.io integrates WebSocket and xhr-polling (long polling) and many other modes of communication
1. Setting up node environment
From node website, I choose the window of the MSI one-click Installation. You will also need to configure the system environment variable path attribute and add your test address path after you install node. biu~ biu~

2. Install Socket.io
Use NPM install-g socket.io command or download files from Socket.io website into node_modules folder

3. Service-Side Code Server.js

/* Modules Introduction/var Express = require (' Express '), Sio = require (' Socket.io '), Fs=require (' FS '), PA

th = require (' path ') URL = require (' URL '); =========================app configuration =============================/** * App configuration */var app = Module.export = Express.createser
Ver ();
================= Configuration socket.io=========================/** * Configuration Socket.io */var io = sio.listen (APP);

Assuming IO is the Socket.io server object Io.configure (function () {///io.set ("transports", ["WebSocket"]); ===================socket link Monitor =================/** * Start Socket link Monitor * @param {Object} socket/Io.sockets.on (' Connecti On ', function (socket) {//Common information socket.on (' Public message ', function (MSG, FN) {Socket.broadcast.emit
		g);
	FN (true);

	}); Drop the line, disconnect the link processing socket.on (' Disconnect ', function () {socket.broadcast.emit (' public message ', ' </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:3000 ');
		Start connecting to the server Socket.on (' Connect ', function () {$ (' #connecting '). fadeout ();

	Show (' Connect server succeeded ')});
	Receives the public message Socket.on (' Public messages ', function (msg) {Show (msg);

	});
		$ (' #btn '). Click (function () {var msg = $ (' #content '). Val ();
			Send public message socket.emit (' Common messages ', 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" > is 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-side command first: node server.js

Customer access client.html address like http://localhost/.../chat.html
Here are the results of Firefox and Chrome

PS: At present, Firebox does not support the WebSocket protocol, with the xhr-polling, Chrome is the standard websocket protocol
Pictures intercepted from the node server below

Now the standard of websocket is not yet determined, and different browsers support the handshake protocol. In short, it is not recommended to use WebSocket, 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.