Implement chat Room (Node) based on WebSocket

Source: Internet
Author: User
Tags sendmsg node server

Implement chat Room (Node) based on WebSocket

WebSocket is a TCP-based long-connection communication protocol, the server can actively transfer data to the front end, compared to the Ajax polling server, websocket use the way of monitoring, reduce the pressure

This article as a learning websocket practice, to realize the function of online chat

Service side

Server.js

Consthttp= require(' http ')ConstFs= require(' FS ')ConstWs= require(' ws ')//Create a service LetServer= http.Createserver(function(req,Res{    Res.Writehead( $, {' Content-type ': ' Text/html;charset=utf8 '})//Display page contents    FS.ReadFile("Index.html", function(Err,Data{        if(ERR)return Console.Error(ERR);        Res.End(data)});}).Listen(8000)//server-defined Web socket server LetWss= New ws.Server({Server})//Store socket LetClientmap= {}//Counter LetCount= 0//Customer ID LetId= 0 LetD= New Date()when the client connects to the server, the callback function accepts a socket objectWSS. on("Connection", function(socket){Count++;Id++;    //Add Users    Socket.ID =ID Clientmap[id]=SocketConsole.Log("section" +Count+ "The user is online, id is" +IdSocket.Send("Welcome to the chat room, already there"+Count+"People online")//Listening to client data    Socket. on("Message", function(msg){        //Broadcast messages         for( LetIdinchCLIENTMAP){            Console.Log(ID)Console.Log(Socket.ID)if(ID=== Socket.ID.toString()) Clientmap[id].Send(D.tolocaletimestring()+ "I:"+MsgElseClientmap[id].Send(D.tolocaletimestring()+ " " + Socket.ID +"No.:"+Msg}    })//Monitor customer downline    Socket. on("Close", function(e){        //delete userCount--;        Console.Log(Socket.ID + "Number of users"  + "Offline")Deleteclientmap[Socket.ID]})//Wrong connection    Socket. on("Error", function(ERR){        Console.Log("Client connection Error" +Err})})
Client

Index.html

<!DOCTYPE html><HTML lang="en"><Head>    <Meta CharSet="UTF-8">    <Meta name="Viewport"Content="Width=device-width, initial-scale=1.0">    <Meta HTTP-Equiv="X-ua-compatible"Content="Ie=edge">    <Title>Chat room</title><style>#room {Border:solid;margin:2px;width:400px;height:500px;overflow-y: scroll;        }</style></head><body><div id= "Hostel" ></div>    <input type="Text"Id="MSG">    <Button ID="Send">Send</button><!--client Script --<script>//Define Web socket clientLet WSC = new WebSocket("ws://localhost:8000")Let Servererror = FalseLet's = document.getElementById(" the Hostel")Let inputtext = document.getElementById("MSG")//Establish connectionWsc.onopen = function(e) {Console.log(' successfully entered the chat room ')        }//Get back-end messageswsc.onmessage = function(e) {room.innerhtml+= ' <p> '+E.data+' </p>'}//Off        WSC.OnClose = function(e){            Alert("chat room is closed") Servererror= true        }        //Error        WSC.onerror = function(){            Console.Log("Connection Error")}        //Send informationSendmsg= function(){             LetS= Inputtext.value            if(Servererror){                Alert("chat room is closed")}            Else if(msg.value === ""){    //alert ("Send content cannot be empty")            } Else {                WSC.Send(s)Inputtext.value = ""            }        }        //Register event to send information        Send.onclick =SendmsgDocument.onkeydown = function(EVT){            if(Cv2.Code === "Enter")sendmsg()};    </script></body></html>
Run results

Run

node server.js

Open different browser, or the same browser multiple tab, access to localhost:8000, you can intern chat function

Service-Side output:

study node server.js第1位用户上线了,ID为1第2位用户上线了,ID为2第3位用户上线了,ID为33号用户下线2号用户下线1号用户下线
Summary

Feel websocket very elegant, back-end become active only good ~

Implement chat Room (Node) based on WebSocket

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.