Project introduction

A simple chat room based on Websocket

IO + inanimate. CSS + Angular doesn’t understand websocket. Socket. Github project address

Installation and use

Git clone https://github.com/ShanaMaid/websocket-express-webchat.git # download project NPM install # installation depends on the node app. Js # start service access http://localhost/ # Enter the chat roomCopy the code

function

  • Room entry Notification
  • Leave room notice
  • Message receiving and sending
  • Online list
  • Backup server information

Animated gifs

The chat room

Online chat room Demo

Mobile phone and computer access, click me to access the online version

implementation

Train of thought

Using the ON binding event, the emit triggers the binding event and the server interacts with the client

Socket. On (eventName,callBack) # Bind event, eventName can define socket. Emit (eventName,data) # trigger event, send dataCopy the code

For more information on socket. IO, please visit the official documentation.

The service side

First add the modules we need to use

var express = require('express');
var socket = require('socket.io');
var fs = require('fs');Copy the code

Then read some configuration information we need about the chat room from the config file config.json, about the config file

var history_num = config.history_num ; Var port = config.sever_port; Var backup = config.backup; Var backup_filename = config.backup_filename; // Backup file nameCopy the code

Define the person and History arrays to store the names of online people and the number of messages cached by the server (i.e. the number of historical messages pushed by users when they first entered the chat room)

var person = []; Var history = []; // The message to be cachedCopy the code

Listen on the port number to create a socket object IO

var app = express();
var server = app.listen(port);
var io = new socket(server);
Copy the code

Write the connection event, respond to the client’s connection request, return the client socket, write the event that the client wants to emit ………………………… Click the Github project address for complete code

IO. On ('connection', (socket) => {………………………… socket.emit('history',history); Send IO. Sockets. Emit ('updatePerson', person); UpdatePerson events are triggered on all clients to update the online list staff ………………………… Socket. On (' sendMsg, (data) = > {# send message event................................................ io.sockets.emit('news',obj); Broadcast, trigger all client news events, update information. }); Socket. On (' setUserName, (data) = > {# set user name events................................................ io.sockets.emit('updatePerson',person); Io.sockets. Emit ('news',{content:user+' enter room ',time:Now(),name:' system message '}); # Broadcast, trigger all client news events, notification into the room ………………………… }); Socket. on('disconnect', (socket) => {# drop event if(user! = ' ') {(IO) sockets) emit (' news' {content: user + 'out of the room, the time, Now (), name:' system messages'}); Person.splice (id,1); person.splice(id,1); } io.sockets.emit('updatePerson', person); }); });Copy the code

The client

Variable initialization

$scope.data = []; $scope.name = "; $scope. Content = ''; $scope.personnum = 0; $scope. Personlist = []; $scope.flag = false; # NameCopy the code

Create a client socket

const socket_url = 'http://localhost';
var socket = io(socket_url);
Copy the code

Complete the emit event on the server side

Socket. on('news', (data) => {…………………… }); Socket. On ('history', (data) => {…………………… }); Socket. On ('updatePerson', (data) => {…………………… });Copy the code

Config. json configuration file

{"history_num":20, "sever_port":80, "backup":true, "Backup_filename ":"./backup/example.json"Copy the code

Chat Message Backup

The chat messages are stored in json format in example.json!

function backupMsg(filename,obj) { var backup_file = fs.readFileSync(backup_filename); var msg= backup_file! = ' '? JSON.parse(backup_file) : []; msg.push(obj); var str = '[\n' msg.forEach((value,index) =>{ if (index! ==0){ str+=',\n';  } str += ' {\n "name":"'+value.name+'",\n "time":"'+value.time+'",\n "content":"'+value.content+'"\n }' } );  str += '\n]'; fs.writeFile(filename, str, (err) => { if(err) console.log("fail write :" + arr + " "+Date() + "\n error:"+err); }); }Copy the code

Backup Information Example

[{" name ":" the tester 1 ", "time", "the 2017-2-13 23:32:17", "content" : "a simple test message"}, {" name ":" test man 2 ", "time", "the 2017-2-13 23:33:42", "Content" : "that you're terrific oh"}, {" name ":" test 3 ", "time", "the 2017-2-13 23:33:54", "content" : "really well"}]Copy the code

conclusion

Websocket implements full duplex communication between browser and server. For example, the original polling mechanism looks like this:

Client: Server, do you have any message for me? Server: Yes. Client: Server, do you have any message for me? Server: No. —————————— infinite repeat ———————————— client: Server, do you have a message for me? Server: No. Client: Server, do you have any message for me? Server: you are not vexed ~Copy the code

Now websocket:

Client: Server, please call me when you hear from me. Server: OK! —————————— when there is a message ———————— server: there is a message for you, client. Client: Received.Copy the code

Github project address, welcome to exchange and study!

Alipay rewards