socket.io achieve more than chat

1, the back-end environment to build

# NPM heat
# npm install -s express
# npm install -s socket.io 

npm init generates json file as dependencies, and Express socket.io plug after installation is generated node_modules folders and package-lock.json lock dependence file recorded version of the plug.

Completion of the above steps and create index.js file as an entry document backend.

2, the rear end of an entry file

1) In the index, within js necessary to introduce the already installed plug-ins

/ * Introducing widget * / 
const Express = the require ( 'Express' )
const socket = require('socket.io')
const app = express()

2) need to set up cross-domain access

/ * Set domain access * / 
app.all ( '*', function (REQ, RES, Next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

3) Listening port number and responds to the request reception

/ * Listening port number * / 
const Server = app.listen (4000, () => {
  console.log ( '4000 port is listening ...' )
})
/ * Listen for front-end request event * / 
const IO = socket (Server)
NUM the let = 0 // total number of online 
io.on ( 'Connection', (Socket) => {
     // response to the connection (Response Body) 
}

The current station using io.connect () when the connection port number, and the rear end will be monitored response. The following code in response vivo

4) in response to body - listening on the line XX

= auther the let null  // the name of the informant 
NUM ++
 // the line 
socket.on ( 'Online', (name) => {
  the console.log (name + 'on-line' )
  auther = name
  const obj = {
    whether, whether,
    name: name
  }
  io.sockets.emit('online',obj)
})

When a certain on-line, you need to first add a total number of on-line, will soon pass the name name to the online event, backstage listening to the online event, the name of the informant recorded on the foreground to the background after the connection is completed, this is mainly used in the subsequent offline. The information is then broadcast to a certain line on all pages (including myself) have been connected by io.sockets.

5) thereof in response - certain listener is input

// listener is input ... 
socket.on ( 'Typing', (name) => {
  socket.broadcast.emit('typing',name)
});

When a certain input in the input tag content, will be sent to the background typing the name of the event, listener typing the background and response, through socket.broadcast broadcast to all pages (except their own)

6) response body - listening, speaking

// received statement and return 
  socket.on ( 'Chat', (Data) => {
    io.sockets.emit('chat',data)
    console.log(data)
  });

 

Send certain information (name and content) in the foreground to the background chat events, chat backstage monitor and respond to events, will broadcast information to all pages.

7) in response thereof - listening offline

// listening offline ... 
  socket.on ( 'the disconnect', () => {
    the console.log (auther + '... offline' )
    Surely - 
    const obj = {
      whether, whether,
      name: auther
    }
    io.sockets.emit('offline',obj)
  });

Front page disconnect when leaving the trigger event, the background to listen and respond to the disconnect event, will broadcast the total number of previously saved names and minus one online for all pages. Here, all the back-end logic was already ready to start the back-end .......

3, a request reception member

The front page written using vue,

After 1) introduced socket.io (introduced in the root page index.html vue project), you can use the introduction io

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.dev.js"></script>

2) need to be in the home of Mr. own name (and here I randomly generated name), connected to the background and the name passed back and tell the other page so and so joined chat. Here I've created a class for handling connection background, the class once created, constructor will be executed, so it will connect back and pass the name to the background, the background listening online and receive data, and then broadcast to all pages.

this.auther = '阿' + Math.floor(Math.random()*20)
this.chat = new Chat(this.auther)
//类chat内有connect方法
connect() {
 this.socket = io.connect('http://10.112.169.51:4000')
 this.socket.emit('online',this.name)
}

3) to receive a certain on-line, online event has been triggered to the background, then the need to receive a certain number of on-line and on-line broadcast background

the this .chat.socket.on ( 'Online', (obj) => {
   the this .title = `online users ($ {obj.num} person)`
   the this .keypress = `$` join the chat} {obj.name
})

4) is receiving input, when input values ​​have need to pass the name of the background, the background will be broadcast to all pages and the need to receive data broadcasting

watch: {
  value() {
    this.chat.socket.emit('typing', this.value.trim() ? this.auther : '')
  }
},

this.chat.socket.on('typing',(data)=>{

  this.keypress = data data + 'is typing ...':? ''

})

5) receiving the statement, the front desk will speak the name and information to pass back through the Send button, backstage broadcast to all pages, all need to receive broadcast information

this.chat.socket.on('chat',(data)=>{
   this.list.push({
     imgUrl: require('@/assets/styles/images/asan.jpg'),
     auther: data.name,
     content: data.value,
     self: data.name === this.auther
   })
   setTimeout(()=>{
     if(this.scroll.maxScrollY) this.scroll.scrollTo(0,this.scroll.maxScrollY)
   },100)
})

6) offline processing, the front desk when leaving the page will tell backstage disconnected. This, the main logic reception has been completed (since only attach the main logic, specific code can look at my github foreground , github background ), started the reception

disconnect() {
  this.socket.disconnect()
}

4, a flowchart

5, the effect of FIG.

 

 6, reference

https://socket.io/docs/

https://hackernoon.com/an-overview-of-frontend-and-backend-interaction-48l031ba

Guess you like

Origin www.cnblogs.com/Ladai/p/11704149.html