Usage scenarios: chat rooms; permanent interaction large amounts of data;
Technology stack: Node.js, Vue.js || native JS
Server code:
App the require = const ( 'HTTP' ) .createServer () const IO = the require ( 'Socket.IO' ) (App) app.listen ( 8877 ) io.on ( 'Connection', Scoket => { the let I =. 1 const T = the setInterval (() => { I ++ IF (I> = 12 is ) { the clearInterval (T) } // server sends a message to the client scoket.emit ( 'news', {hello : 'world', t : new new . a Date () the getTime ()}) }, 1000 ) // server listening client message scoket.on ( 'receiveEvent', data = > { console.log('receiveEvent: ', data) }) })
Client code:
- Vue example:
<template> <div> <p @click="clientToServer">scoket:</p> <p v-for="(item,index) in arr" :key="index">{{item}}</p> </div> </template> <script> import io from 'socket.io-client' export default { beforeMount() { // 初始化 客户端 socket this.socket = io('http://localhost:8877') }, data() { return { arr: [] } }, mounted() { // 监听服务端 scoket 'news' 数据流 this.socket.on('news', data => { this.arr.push (Data) }) }, Methods: { // the client sends a message to the server ClientToServer () { the this .socket.emit ( 'receiveEvent', '~ IM from the clientSide the Hi' ) } }, // destruction Socket beforeDestroy () { the this .socket.close ( 'News' ) } } </ Script>
- Native Code Example:
<!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>Socket Demo</title> </head> <body> <button>Send Msg</button> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script> <script> const wsUrl = "http://localhost:8877"; window.onload = () =>listening message server//io.connect (wsUrl); = Const Socket{ socket.on("news", data => { console.log("news: ", data); }); // 往服务端发送消息 document.getElementsByTagName('button')[0].onclick = function() { socket.emit('receiveEvent', 'msg from client!') } }; </script> </html>
Something (Note):
Here is Node.js socket.io use third-party libraries, I tried after pm2 cluster deployment, because the characteristics of multi-core operation, resulting in the session id socket error, have not been treated well, if God made similar big deal, Please advise the exchange! ! !