Websocket+node.js Web chat server to create instant Messaging _node.js

Source: Internet
Author: User
Tags readfile

This article node.js to create an Instant Messaging Web chat server for your reference, the details are as follows

1. Use of Nodejs-websocket
Nodejs-websocket is a library of backend implementation WebSocket protocol based on Node.js.
Connection:https://github.com/sitegui/nodejs-websocket.
(1) installation
installed in the project directory via NPM: NPM install Nodejs-websocket
(2) Create a server

 Introduction of Nodejs-websocket
var ws = Require ("Nodejs-websocket");
Call the Createserver method to create the server, and the conn in the callback function is the instance of connection
var server = ws.create (function (conn) {
  Console.log ("New Connection ");
  Listens for text events, which are triggered whenever text type data is received from the server, and the callback function's arguments are string
  conn.on ("Text", function (str) {
 Console.log (" Received "+ str);
  };
  Listens on the close event, triggering
  Conn.on ("Close", function (code, reason) {
 console.log ("Connection closed"), each time the connection is disconnected)
} ). Listen (8888);

2. Client Use WebSocket
the client first needs to instantiate a WebSocket object: ws = new WebSocket ("ws://localhost:5000"), where the parameters are passed in the format Ws://+url, which is the same as the HTTP protocol prefix http://. The next step is to use the WebSocket built-in methods for event monitoring and data presentation.
This is a unified description of each listening event: OnOpen When a connection is established between the server and the client, onmessage when the client receives data sent by the server, onclose when the connection to the client and server is closed, and onerror when a connection error occurs.

3. Use Websocket+nodejs to realize online chat room
(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 the binary type, where binary data is sent and read through the stream's mode/var app=require (' http '). Createserver ( handler);
In order to simplify the code, put the server to create 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 where the file resides.
      Invokes the ReadFile method for file read 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 in port 8888//conn is the corresponding connection instance var server = Ws.createserver (function (conn) {Console.log (' new
  Conneciton ');
  Listens on the text event, triggering conn.on ("text", function (str) {broadcast (SERVER,STR) whenever text is received;
  }); triggered when any one end closes the connection, here is the console output connection closed Conn.on ("Close", function (Code,reason) {console.log (' connection closed ')
  ;
}). Listen (5000); Note that the listen listening here is the port of the server that was just opened, and the client sends the message here to handle function broadcast (server, MSG) {// Server.connections is an array that contains all the incoming client Server.connections.forEach (function (conn) {//
  The Connection.sendtext method can send the specified content to the client, passing in a string//here for traversing each client to send its content conn.sendtext (msg);
 }) above is the article

The whole content of the

, hope to be helpful to everybody's study, also hope everybody support cloud habitat community more.

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.