当前位置:网站首页>Websocket (basic)
Websocket (basic)
2022-04-23 17:14:00 【MiMenge】
What is? WebSocket?
WebSocket Is based on TCP/IP agreement , Independent of HTTP Protocol communication protocol .
WebSocket It's two-way communication , A stateful , Client 1 ( many ) One with the server ( many ) Bidirectional real-time response ( client ⇄ Server side ).
WebSocket It is applied in the browser Socket ( yes Socket Implementation of model interface ),Socket Is a network communication interface ( Communication specifications ).
WebSocket The protocol port is 80.
WebSocket SSL The protocol port is 443.
Socket yes TCP/IP Network data communication interface of protocol ( An underlying means of communication ).
Socket yes IP Combination of address and port number . for example :192.168.1.100:8080.
WebSocket The role of
Full duplex with the server is realized through a long-term connection 、 Full two-way communication .
Popular said Is to establish a connection between the server and the client , A certain connection is established between them . The server can send requests to the client , However The server can also send requests to the client
. Before breaking http In the connected state, the client can only send requests to the server .
Create a WebSocket when , One Http Service to initialize the connection . After the server responds , Link using http Head from http The protocol switches to websocket agreement (Upgrade).
because WebSocket Using custom protocol , therefore Url The plan will change , No more use http://, https://
Need to use ws://, wss://. The former is an insecure connection , The latter is a secure connection .
Advantages of using custom protocols
The client and server can send very little data , It won't be right http Cause any burden . It can be used in applications with great impact on bandwidth and delay ( The packet size is small ). Not affected by homologous strategies
shortcoming
Longer definition time
Use WebSocket
establish
let ws = new WebSocket('ws://www.awdz.com/server.php');
adopt new establish websocket, What's coming in url It's the absolute path . Because it is not affected by the homology strategy . So you can open the connection of any site .
When the initialization websocket after , The browser will immediately create a connection .
websocket There is also a readyState
value | state |
---|---|
WebSocket.opening(0) | Connection is being established |
WebSocket.open(1) | Connection established |
WebSocket.closeing(2) | The connection is closing |
WebSocket.close(3) | Connection closed |
apis
api | describe |
---|---|
send | Send to socket Service data |
event
event | describe |
---|---|
onopen | Trigger when the connection is successful |
onerror | Trigger... When connection error occurs |
onclose | Trigger... When the connection is closed |
onmessage | Triggered when the service response data is received |
close WebSocket Methods
.close()
Method
let ws = new WebSocket('wss://123.123.1.3:22/ww.txt');
// Close the connection
ws.close();
Send request to server , Receive request from server
Build on the server websocket service ( A very humble chat room )
You need to use npm A download process websocket Third party modules for services
$ npm install nodejs-websocket -s
After downloading, introduce the module
const socketConn = require('nodejs-websocket');
establish socket service
const socketConnet = socket.createServer(conn => {
});
Listening port
socketConnet.listen(4400, err => {
if (err) {
throw new Error('socket Boot failure ');
}
console.log('socket Successful launch ');
});
monitor socket state
// Create a broadcast
socketConnet.connections.forEach(item => {
item.sendText(' Number of people online in chat rooms ' + socketConnet.connections.length)
});
// monitor socket The connection of is closed
conn.on('close', () => {
console.log(' Connection is closed ');
console.log(socketConnet.connections.length);
socketConnet.connections.forEach(item => {
item.sendText(' Number of people online in chat rooms ' + socketConnet.connections.length)
});
});
// Receive requests from clients
conn.on('text', (data) => {
conn.sendText(' Play a role ' + JSON.parse(data));
})
// Listen for the disconnection abnormal state of the connection
conn.on('error', () => {
// console.log('err');
})
Complete code
const socket = require('nodejs-websocket');
const socketConnet = socket.createServer(conn => {
// Create a broadcast
socketConnet.connections.forEach(item => {
item.sendText(JSON.stringify({
key: 001, value: ' Number of people online in chat rooms ' + socketConnet.connections.length
}))
});
// monitor socket The connection of is closed
conn.on('close', () => {
socketConnet.connections.forEach(item => {
item.sendText(JSON.stringify({
key: 001, value: ' Number of people online in chat rooms ' + socketConnet.connections.length
}))
});
});
// Receive requests from clients
conn.on('text', (data) => {
let userData = {
key: conn.key,
value: data
}
// Broadcast distribution
socketConnet.connections.forEach(item => {
item.sendText(JSON.stringify(userData));
});
})
// Listen for the disconnection abnormal state of the connection
conn.on('error', () => {
})
});
// Listening port
socketConnet.listen(3300, err => {
if (err) {
throw new Error('socket Boot failure ');
}
console.log('socket Successful launch ');
});
Use on client webSocket
establish websocket service
let socket = new WebSocket('ws://localhost:4400');
event
// establish websocket
let socket = new WebSocket('ws://192.168.2.97:3300');
let chatRoom = document.querySelector('.chatRoom');
let input = document.querySelector('input');
let ul = document.querySelector('ul');
// socket Triggered on successful connection
socket.onopen = function () {
console.log(' Successful connection ');
}
// socket Triggered when the connection is closed
socket.onclose = function () {
console.log(' Connection is broken ');
}
// socket Triggered when the connection fails
socket.onerror = function (err) {
console.log(' The connection fails ' + err);
// Close connection on failure
socket.close();
}
// receive socket The server's response or request
socket.onmessage = function (message) {
// console.log(message);
if (message && JSON.parse(message.data).key) {
if (JSON.parse(message.data).key === 1) {
chatRoom.innerText = JSON.parse(message.data).value;
} else {
let li = document.createElement('li');
li.innerHTML = ` <div class="name">${
JSON.parse(message.data).key}</div> <p>${
JSON.parse(message.data).value}</p> `;
ul.appendChild(li);
}
} else {
}
}
let buttons = document.querySelectorAll('button');
buttons[0].onclick = function () {
if (input.value.trim()) {
socket.send(input.value);
input.value = ''
} else {
confirm(' Input cannot be empty !');
}
}
buttons[1].onclick = function () {
socket.close();
confirm(' Disconnected ');
}
close Method can be closed socket Connect
All the code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.phone {
width: 300px;
height: 600px;
padding: 20px;
margin: 0 auto;
border-radius: 10px;
border: 1px solid #ff0;
}
div.show {
position: relative;
width: 300px;
height: 560px;
border-radius: 10px;
border: 1px solid #111;
}
p.chatRoom {
width: 100%;
height: 40px;
line-height: 40px;
text-align: center;
border-radius: 10px;
background-color: rgba(255, 255, 0, 0.473);
}
.kuang {
width: 100%;
overflow-y: auto;
height: calc(100% - 80px);
}
ul {
width: 100%;
}
li {
width: 100%;
min-height: 60px;
margin-bottom: 10px;
background-color: rgb(247, 245, 245);
}
.name {
width: 100%;
height: 20px;
color: red;
}
li>p {
width: calc(100%-20px);
padding: 0 10px;
min-height: 40px;
border: 1px solid #ccc;
word-wrap: break-word;
}
input {
position: absolute;
bottom: 0;
width: 200px;
height: 30px;
}
</style>
</head>
<body>
<div class="phone">
<div class="show">
<p class="chatRoom">
</p>
<div class="kuang">
<ul>
</ul>
</div>
<input type="text">
</div>
<button> Send a message </button>
<button> close websocket</button>
</div>
<script>
// establish websocket
let socket = new WebSocket('ws://192.168.2.97:3300');
let chatRoom = document.querySelector('.chatRoom');
let input = document.querySelector('input');
let ul = document.querySelector('ul');
// socket Triggered on successful connection
socket.onopen = function () {
console.log(' Successful connection ');
}
// socket Triggered when the connection is closed
socket.onclose = function () {
console.log(' Connection is broken ');
}
// socket Triggered when the connection fails
socket.onerror = function (err) {
console.log(' The connection fails ' + err);
// Close connection on failure
socket.close();
}
// receive socket The server's response or request
socket.onmessage = function (message) {
// console.log(message);
if (message && JSON.parse(message.data).key) {
if (JSON.parse(message.data).key === 1) {
chatRoom.innerText = JSON.parse(message.data).value;
} else {
let li = document.createElement('li');
li.innerHTML = ` <div class="name">${
JSON.parse(message.data).key}</div> <p>${
JSON.parse(message.data).value}</p> `;
ul.appendChild(li);
}
} else {
}
}
let buttons = document.querySelectorAll('button');
buttons[0].onclick = function () {
if (input.value.trim()) {
socket.send(input.value);
input.value = ''
} else {
confirm(' Input cannot be empty !');
}
}
buttons[1].onclick = function () {
socket.close();
confirm(' Disconnected ');
}
</script>
</body>
</html>
Mount static pages
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
app.get('/', (request, response) => {
fs.readFile(path.join(__dirname + '/public/index.html'), (err, data) => {
if (err) {
response.end('<h1>404~</h1>');
return;
}
response.end(data);
});
});
app.listen(4400, err => {
if (err) {
console.log(err);
return;
}
console.log(' Service started successfully ');
});
版权声明
本文为[MiMenge]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230553027710.html
边栏推荐
猜你喜欢
.Net Core3. 1 use razorengine NETCORE production entity generator (MVC web version)
Understanding of RPC core concepts
文件操作《二》(5000字总结篇)
Document operation II (5000 word summary)
Using quartz under. Net core - [1] quick start
Go language, array, string, slice
[logical fallacy in life] Scarecrow fallacy and inability to refute are not proof
C语言函数详解
01-初识sketch-sketch优势
2.Electron之HelloWorld
随机推荐
Promise (II)
Clickhouse SQL operation
PHP efficiently reads large files and processes data
Interface document yaml
Linux MySQL data timing dump
XTask与Kotlin Coroutine的使用对比
Detailed explanation of the penetration of network security in the shooting range
【WPF绑定3】 ListView基础绑定和数据模板绑定
Baidu Map Case - modify map style
[PROJECT] small hat takeout (8)
【解决报错】Error in v-on handler: “TypeError: Cannot read property ‘resetFields’ of undefined”
1-3 components and modules
freeCodeCamp----prob_ Calculator exercise
Use of shell cut command
Scope and scope chain in JS
Further optimize Baidu map data visualization
SQL: How to parse Microsoft Transact-SQL Statements in C# and to match the column aliases of a view
Using quartz under. Net core -- a simple trigger of [7] operation and trigger
ASP. NET CORE3. 1. Solution to login failure after identity registers users
ASP. Net core reads the configuration file in the class library project