Based on Websocet simple chat room (Nodejs + node-websocket-server) __web

Source: Internet
Author: User
Tags install node
based on Websocet simple chat room (Nodejs + node-websocket-server)3 People collection This article, collection of this article published 24 days ago, there have been 135Times read a total 2A comment 3People to collect this article

Recently in the study of HTML5 related things, see WebSocket is a very powerful technology, so a small try, made a simple chat room.

WebSocket principle is not much introduced, if you want to realize the WebSocket server, the specific agreement look here: Bash (do not know you reader can look down, anyway, I did not see.) )

First, the operating environment

1, Service end: The previous stage to see Oschina on the introduction of Nodejs, feeling is a very good stuff, both before and after the table with JS should be a very good feeling it, haha: P. Since the use of websocket, of course, to see how to let Nodejs support WebSocket. After the search found Node-websocket-server is a websocket implementation of Nodejs, installed Node-websocket-server we can start. But I install node-websocket-server when but a little bit of trouble, for other children's shoes less detours I here is simple to say:

Linux installation is relatively simple, first install NPM, command (Curl http://npmjs.org/install.sh | SH): After installing NPM, enter your project development directory and then perform NPM install Websocket-server to install Node-websocket-server.

Because NPM cannot be installed under Windows (unless you are using Cygwin ...). It wouldn't be too much trouble. And don't know the directory structure of the Nodejs module, so there is no way to install it again in the arch with NPM. After installation found that its directory structure is as follows: In the project directory to build a node_modules directory, open Node_modules can see a websocket-server directory .... Is it possible to follow such a directory structure under Windows? So decisively to the Windows test, download Websocket-server plug-in (address), after decompression according to the above directory after the start of the Nodejs, sure enough; The use of Node-websocket-server is also very simple, see more: Bash

The following is the beginning of the code ...

Second, the service-side implementation

Simple description: Create an array to hold all links to the server, and send this message to other clients when a message from the client is received. View Source print?

01 var Conns = new Array ();
02
03 var ws = Require (' Websocket-server ');
04
05 var server = Ws.createserver ();
06
07 Server.addlistener (' Connection ', function (conn) {
08 Console.log (' connection ... ');
09
10 Conns.push (conn);
11
12 Conn.addlistener (' message ', function (msg) {
13
14 Console.log (msg);
15
16 for (var i=0; i<conns.length; i++) {
17 if (conns[i]!=conn) {
18 Conns[i].send (msg);
19 }
20 }
21st });
22 });
23
24 Server.listen (8080);
25 Console.log (' running ... ');

Third, the client implementation

When received the message will be sounded the classic sentence: You have a new message, please pay attention to check

View Source print?

01
02
03 <script type= "Text/javascript" >
04 var host = ' 127.0.0.1 ';
05 var port = 8080;
06 var url = ' ws://' +host+ ': ' +port+ '/';
07
08 var w = new WebSocket (URL);
09
10 var audioelement = document.createelement (' audio ');
11 Audioelement.setattribute (' src ', ' Qqmsg.mp3 ');
12
13 W.onopen = function () {
14 $ (' Chat-box '). InnerHTML = ' connected to server ......<br/> ';
15 }
16
17 W.onmessage = function (e) {
18 var msg = E.data;
19 var chatbox = $ (' Chat-box ');
20
21st Audioelement.play ();
22 chatbox.innerhtml = chatbox.innerhtml+msg+ ' <br/> ';
23 }
24
25 function Send () {
26 var talk = $ (' Talk ');
27 var Nike = $ (' Nike ');
28
29 W.send (' <strong style= ' color:red ' > ' +nike.value+ ':</strong> ' +talk.value);
30 }
31 function $ (ID) {
32 return document.getElementById (ID);
33 }
34 </script>
35
36
37 <body>
38 <div id= "Chat-box" style= "bordddder:1px solid #cccccc; width:400px; height:400px; Overflow:scroll; " ></div>
39 Nickname: <input type= "text" id= "Nike"/><br/>
40 Content: <input type= "text" id= "talk"/><input type= "button" id= "Send" onclick= "Send ();" value= "Send"/>
41 </body>
42

Four, the Operation effect

V. Summary

The example above is tested and developed under Chrome and not tested by other browsers.

With WebSocket we can easily implement features that were difficult to implement before. And Nodejs also let a person in front of a bright, before and after the table with JS feeling quite cool ah. Really like Nodejs, also recommended that everyone try it, very easy to use.

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.