socket.io

Socket. IO official website document

The service side

The server mainly realizes an information forwarding station, similar to the work of information A -> Server -> Information B process.

  1. Create a folder, Demo, and run NPM init in that folder to initialize a project.
  2. Install the Express, socket. IO moduleNPM install [email protected]; npm install socket.io
  3. Index.js code to implement a simple service:
const { Server } = require('http'); var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var port = process.env.PORT || 3200; IO. On ('connection', function(socket){// Listen on socket. On ('message', function(MSG){// listen on message IO. MSG) // Send message}); }); Http.listen (port, function(){console.log(' Listening on *:' + port); });Copy the code

The client

Receives the information sent by the server and the user. Create static index. HTML

/ / reference < script SRC = "https://cdn.socket.io/socket.io-1.2.0.js" > < / script > < script > var socket = io('http://localhost:3200'); If (socket) {socket.on('message', (MSG)=>{// message is the same as the service. Log ('message:', MSG)})} // Send message socket.emit('message', 'hi'); </script>Copy the code

code

Nginx deployment

Install the node

Wget https://nodejs.org/dist/v12.18.1/node-v12.18.1-linux-x64.tar.xz tar xf node - v12.18.1 - Linux - x64. Tar. Xz CD Node - v12.18.1 - Linux - x64Copy the code

Configuring the Node Environment

Bak export PATH=$PATH:/root/node-v12.18.1-linux-x64/bin source /etc/profileCopy the code

The test environment

node -v
Copy the code

Running the server

Put server-side code on the server

The installation of forever

NPM install forever -g forever start index.js // Enable forever Stop index.js // stopCopy the code

Configure the nginx file

# 80 port location /socket. IO / {proxy_http_version 1.1; Proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; Proxy_pass http://127.0.0.1:3200; }Copy the code

Client IO connection:

Socket = IO (' WSS :// domain name /');Copy the code