WebSocket + node. js: Create an instant messaging Web chat server, websocketnode. js

Source: Internet
Author: User

WebSocket + node. js: Create an instant messaging Web chat server, websocketnode. js

In this example, node. js creates an instant messaging Web chat server for your reference. The details are as follows:

1. Use nodejs-websocket
Nodejs-websocket is a backend library that implements the websocket protocol based on node. js,
Connection: https://github.com/sitegui/nodejs-websocket.
(1) Installation
Install: npm install nodejs-websocket in the project directory
(2) create a server

// Introduce nodejs-websocketvar ws = require ("nodejs-websocket"); // call the createServer method to create a server. the conn in the callback function is the connection instance var server = ws. create (function (conn) {console. log ("New connection"); // listens for text events. A text event is triggered whenever the server receives text data. The callback function parameter is the passed string conn. on ("text", function (str) {console. log ("disconnected ed" + str) ;}); // listens for the close event, triggering conn each time the connection is closed. on ("close", function (code, reason) {console. log ("Connection closed ");})}). listen (0, 8888 );

 2. The client uses websocket
On the client, you must first instantiate a websocket object: ws = new WebSocket ("ws: // localhost: 5000"). The parameter input format is ws: // + url, this is the same as the http prefix http. Next, we can use some built-in websocket methods for event listening and data presentation.
Here we will introduce all listener events: onopen is triggered when the server and the client establish a connection; onmessage is triggered when the client receives the data sent by the server; onclose is triggered when the connection between the client and the server is closed; onerror is triggered when a connection error occurs.

3. Use websocket + nodejs to implement online chat rooms
(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 transmission: text and binary, binary data is sent and read in stream mode */var app = require ('HTTP '). createServer (handler); // to simplify the code, place the server creation code in the handler function var ws = require ('nodejs-websocket '); var fs = require ('fs'); app. listen (8888); function handler (req, res) {// _ dirname returns the current directory of the file. 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 are successfully rendered on port 8888. The corresponding html interface // conn is the corresponding connection instance var server = ws. createServer (function (conn) {console. log ('new citciton'); // listens for text events. conn is triggered whenever the text is received. on ("text", function (str) {broadcast (server, str) ;}); // triggered when the connection is closed at any end. The connection closed conn is output on the console. on ("close", function (code, reason) {console. log ('Connection closed ');})}). listen (5000); // note that the listen listener is the port of the server you just opened. The client sends the message to function broadcast (server, msg) {// server. connections is an array containing all connected client servers. connections. forEach (function (conn) {// connection. the sendText method can send specified content to the client and input a string // here to traverse each client and send the content conn for it. sendText (msg) ;}} the above is the article

All content, hope to help you learn, and hope you can support the house of helping customers.

Related Article

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.