Websocket+node.js Creating a Web chat server for Instant Messaging

Source: Internet
Author: User
Tags readfile

1. Using Nodejs-websocket
Nodejs-websocket is a library based on a backend implementation of the WebSocket protocol written by node. js.
Connection: Https://github.com/sitegui/nodejs-websocket.
(1) Installation
Installing via NPM in the project directory: NPM install Nodejs-websocket
(2) Creating a server
Introduce Nodejs-websocketvar WS = Require ("Nodejs-websocket");//Call Createserver method to create the server, conn in the callback function is the instance var of connection Server = Ws.create (function (conn) {    Console.log ("New connection");    Listens to the text event, which is triggered whenever the text type data is received from the server, and the parameters of the callback function are the passed string    conn.on ("Text", function (str) {Console.log ("Received" + str );    });    Listen for the Close event, triggering    Conn.on ("Close", function (code, reason) {Console.log ("Connection closed")}) each time the connection is disconnected    . Listen (8888);

2. Client using WebSocket
The client first needs to instantiate a WebSocket object: ws = new WebSocket ("ws://localhost:5000"), where the parameter is passed in the format Ws://+url, which is the same as the HTTP protocol prefix//. Next, you can use the WebSocket built-in methods for event monitoring and data presentation.
Here is a unified description of each listener event: OnOpen triggered when the server and client establish a connection, onmessage when the client receives data sent by the server, OnClose when the client and server connections are closed, onerror when the connection is faulty.

3. Implementing an online chat room using Websocket+nodejs
(1) HTML and CSS code omitted
(2) Client JS:
Oconnect.onclick=function () {        ws=new WebSocket (' ws://localhost:5000 ');         Ws.onopen=function () {             oul.innerhtml+= "<li> client connected </li>";         }        Ws.onmessage=function (evt) {            oul.innerhtml+= "<li>" +evt.data+ "</li>";        }        Ws.onclose=function () {            oul.innerhtml+= "<li> client disconnected </li>";        };        Ws.onerror=function (evt) {            oul.innerhtml+= "<li>" +evt.data+ "</li>";         };    };    Osend.onclick=function () {        if (ws) {           ws.send (oinput.value);        }    }
(3) server-side JS:
/*websocket supports two types of data transfer: The text type and binary type, where binary data is sent and read by the */var app=require (' http ') in the stream mode. Createserver (handler); To simplify the code, place the server creation specific code into the handler function var ws=require (' Nodejs-websocket '); var fs=require (' FS '); App.listen (8888); function Handler (req,res) {//__dirname Returns the current directory in which the file resides. Call the ReadFile method to read the file Fs.readfile (__dirname+ '/index.html ', function (err,data) {if (err) {Res.writehead (500            );        Return res.end (' error ');        } res.writehead (200);    Res.end (data); });} The above steps successfully render the corresponding HTML interface on port 8888//conn is the corresponding connection instance var server = Ws.createserver (function (conn) {Console.log (' new    Conneciton ');    Listens for the text event, triggering conn.on ("text", function (str) {broadcast (SERVER,STR) whenever a literal is received;    }); triggered when either end of the connection is closed, this is the console output connection closed Conn.on ("Close", function (Code,reason) {console.log (' connection closed    '); }). Listen (5000);//Note Here The Listen listener is the port of the server that was just opened, the client sends the message here to handle function broadcast (server, MSG) {// Server.connections is an array that contains all the connected clients Server.conThe Nections.foreach (function (conn) {//connection.sendtext method can send the specified content to the client, passing in a string//here to traverse each client for which to send content C    Onn.sendtext (msg); })}


Websocket+node.js Creating a Web chat server for Instant Messaging

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.