vue+node+socket io realizes multi-person interaction and releases the entire process

vue+node+socket io realizes multi-person interaction and releases the entire process

1. Background

1. The front end uses vue + vuex + socket.io-client

npm install socket.io-client --save-dev

2. The backend uses node + express + socketio

1. Build a node development environment

npm init -y

Install required dependencies

npm install express --save-dev
npm install socket.io-client --save-dev

2. Overview of socket.io usage

1. Sending events

socket.emit('event name', data => {
	// data is the data to be transmitted, which can be boolean, string, number, object, etc.})

2. Listening for events

socket.on('Event name when sending', data => {
	//data sent by the event})

3. Broadcasting Events

// Send to other users (not to yourself)
socket.broadcast.emit('event name', data => {
	// data is the data to be transmitted, which can be boolean, string, number, object, etc.})

3. Development Process

1. Create a socket.js file on the front end to receive socket-related events, as follows

// Import socket.io-client
import io from 'socket.io-client'

// Create a link const socket = io()

// Listening socket.on('connect', () => {
  console.log('Connected to the server successfully!!')
})

> =============The middle part is used to listen to the socket events sent by the backend, for example: =====================
// Enter the room socket.on('enter_room', (data) => {
  // Necessary data can be stored in storage
  localStorage.setItem('counts', JSON.stringify(data))
  store.commit('setData', JSON.parse(localStorage.getItem('data')))
})

// Handle service lost connection socket.on('disconnect', () => {
  console.log('disconnect')
})

2. Backend related code

const app = require('express')()
const http = require('http').Server(app)
var io = require('socket.io')(http)

let onlineUsers = {}
let users = []
let onlineCounts = 0

io.on('connection', socket => {
	// User enters the game socket.on('enter', (data) => 
		// Add user information const sid = socket.id
		socket.name = data.name

		// Add a new user if(!onlineUsers.hasOwnProperty(data.name)) {
			onlineUsers[data.name] = sid
			onlineCounts++
		}
		if (!users.length) {
			users.push({
				name: onlineUsers[sid]
			})
		}

		// Current number of clients let clientsCount = io.sockets.server.engine.clientsCount

		//Send the user list to the current user (corresponding to the front-end monitoring enter_room part of the code)
		io.emit('enter_room', {
			role: data.role,
			users,
			onlineCounts
		})
		// Send new users to other users (not to themselves)
		socket.broadcast.emit('user_enter', data.name)
	})
})

// The backend opens the listening port, and the frontend configures the proxyTable to proxy to the backend server, so that the frontend and backend data can be connected http.listen(port, () => {
	console.log('Backend server started successfully!!!')
})

4. Release and launch

1. Front-end:

1) Install http-server, then connect to the server, enter the server and pull the front-end code of the remote warehouse (usually pulled from the server www directory). If you have not cloned the code, you need to configure the public key on the server before downloading.

Public key configuration

ssh-keygen -t rsa -C "your email"

After generating the public key, enter the file directory where the public key was generated, copy it to the code hosting platform, and then you can clone the code after adding the public key.

2) Package the front-end code and generate the dist file

npm run build

3) Enter dist and execute the command to start the front end

pm2 start http-server ---p specifies the port number

4) Front-end access, server address + port number

2. Backend:

1) Just like the front-end (no need to install http-server), after entering the server, pull the front-end code from the remote warehouse (usually pull it from the www directory of the server). If you have not cloned the code, you need to configure the public key on the server before downloading it.
2) Execute commands

pm2 start index.js (file entry, if your app.js is the file entry, execute app.js) -- -p specifies the port number

Note:

When socket.io is released online, the front end must modify the socket.io proxy address port to the backend port, otherwise it will report 404. The modification location is as follows (here my backend port is 3000)

insert image description here

2. Nginx needs to modify the proxy forwarding address of socket.io, otherwise it will also report 404

insert image description here

Supplement 1.pm2 Common commands

pm2 list // View the pm2 startup list
pm2 stop specifies the port number // Stop pm2 under the current port
pm2 restart specifies the port number // restarts pm2 of the specified port
pm2 delete specifies the port number // delete pm2 in the current window
pm2 start http-server / index.js -- -p specifies the port number // Start the corresponding front-end and back-end

2. Related instructions of nginx in the command line

cd /nginx specified directory
cat nginx.conf // View the contents of the nginx file
vim nginx.conf // Edit nginix. Note that after entering, use "i" to enter the editing mode; "u" to undo the previous editing; "esc" to exit the editing mode; "shift + :" to save and exit

At this point, following the above steps, you can carry out any type of socket-related development. Go and try it. If you have any questions, please leave a message.

This is the end of this article about vue+node+socketio to achieve multi-person interaction and release the entire process online. For more relevant vue socketio to achieve multi-person interaction content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Solution to the problem that vue-socket.io cannot receive data
  • Effective solution to vue-socket.io cross-domain problem
  • Example code of how to use Socket.IO with Vue.js
  • Example code for using socket io with vue-cli
  • Example code for Vue communicating with Node.js via socket.io
  • Vue + socket.io implements a simple chat room sample code

<<:  Detailed explanation of the lock structure in MySQL

>>:  Solution to the timeout problem when installing docker-compose with PIP

Recommend

Perfect Solution for No rc.local File in Linux

Newer Linux distributions no longer have the rc.l...

MySQL detailed single table add, delete, modify and query CRUD statements

MySQL add, delete, modify and query statements 1....

CSS -webkit-box-orient: vertical property lost after compilation

1. Cause The requirement is to display two lines,...

js implements form validation function

This article example shares the specific code of ...

Implementation of socket options in Linux network programming

Socket option function Function: Methods used to ...

Serial and parallel operations in JavaScript

Table of contents 1. Introduction 2. es5 method 3...

HTML Tutorial: HTML horizontal line segment

<br />This tag can display a horizontal line...

Some issues we should pay attention to when designing a web page

Web design, according to personal preferences and ...

In-depth explanation of hidden fields, a new feature of MySQL 8.0

Preface MySQL version 8.0.23 adds a new feature: ...

Script to quickly list all host names (computer names) in the LAN under Linux

Recently, I have a need to list all host names in...

Using JavaScript difference to implement a comparison tool

Preface At work, I need to count the materials su...

Detailed explanation of Mysql self-join query example

This article describes the Mysql self-join query....

A collection of common uses of HTML meta tags

What is a mata tag The <meta> element provi...

JavaScript message box example

Three types of message boxes can be created in Ja...

Detailed examples of Docker-compose networks

Today I experimented with the network settings un...