当前位置:网站首页>WebSocket(简单体验版)
WebSocket(简单体验版)
2022-06-28 02:31:00 【赤蓝紫】
WebSocket(简单体验版)
简介
Web Socket(套接字):就是通过一个长时连接实现与服务器全双工、双向的通信。
Web Socket使用的并不是HTTP协议而是自定义的Web Socket协议,所以如果我们使用Web Socket的时候,URL不再是http://或https://,而是ws://或wss://(但是,实际上是看红宝书才想着玩一下下,在开发中还没试过用这个来开发的)
主要特点:服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息。
使用
实例化
要创建一个新的Web Socket,首先需要实例化一个WebSocket对象。
我们实例化WebSocket对象时,传的参数应该是一个绝对URL,同源策略不适用于WebSocket
const socket = new WebSocket("ws://localhost:8088/mysocket");

http请求会有跨域,但是WebSocket不会跨域
后端express
主要部分都注释了(需要安装 express-ws)
const express = require('express')
const expressWs = require('express-ws')
const app = express()
// 将WebSocket服务加到app里,简单来说就是让app添加了ws方法
expressWs(app)
// 建立WebSocket服务
app.ws('/mysocket', function (ws) {
// ws:建立WebSocket的实例
// 向客户端发送信息
ws.send('你连接成功啦')
})
app.listen(8088, () => {
console.log('ws://localhost:8088')
})

如果连接上了,那么http状态码会是101,因为要切换成ws协议
绑定事件
如果我们,在实例化后就开始发送信息,那就会导致信息发不出,因为还没连接上。这时候我们就得了解一下什么时候能发,进而得了解一下WebSocket的相关事件。
open:在连接成功建立时触发error:在连接发生错误时触发(此时已经不能再发信息了)close:在连接关闭时触发(此时已经不能再发信息了)message:收到消息后触发(收到的消息在事件对象中的data里)
const socket = new WebSocket("ws://localhost:8088/mysocket");
socket.onopen = function () {
console.log("连接建立");
socket.send('hello');
// socket.close()
};
socket.onerror = function () {
console.log("连接发生错误");
};
socket.onclose = function () {
console.log("连接关闭");
};
socket.onmessage = function (e) {
console.log(e)
}


模拟两人对话
上面已经说了,收到消息会触发message事件,所以我们可以在message事件里根据收到的信息发送对应的信息。
客户端:
const socket = new WebSocket("ws://localhost:8088/mysocket");
socket.onopen = function () {
console.log("连接建立");
socket.send('hello');
// socket.close()
};
socket.onerror = function () {
console.log("连接发生错误");
};
socket.onclose = function () {
console.log("连接关闭");
};
socket.onmessage = function ({ data }) {
if (data.includes('你好')) {
socket.send('再见,服务端ddd')
} else if (data.includes('再见')) {
// 调用close()方法关闭WebSocket连接
socket.close()
} else {
socket.send('你好,我是客户端ccc')
}
}
服务器:
const express = require('express')
const expressWs = require('express-ws')
const app = express()
// 将WebSocket服务加到app里,简单来说就是让app添加了ws方法
expressWs(app)
// 建立WebSocket服务
app.ws('/mysocket', function (ws) {
// ws:建立WebSocket的实例
ws.send('你连接成功啦')
ws.onmessage = function ({ data }) {
if (data.includes('你好')) {
ws.send('你好,我是服务器ddd')
} else if (data.includes('再见')) {
ws.send('再见,客户端ccc')
}
}
})
app.listen(8088, () => {
console.log('ws://localhost:8088')
})

注意:如果收发部分处理,需要注意一下,如果没有处理好,可能会出现循环卡住的情况。
比如,服务器和客户端的message事件回调都是:
socket.onmessage = function ({ data }) {
socket.send('hello')
}

边栏推荐
猜你喜欢

暴雨去哪儿?天气预报不准谁的锅?

mysql获取当前时间是一年的第多少天

文件的相对路径写法

More, faster, better and cheaper. Here comes the fastdeploy beta of the low threshold AI deployment tool!

论文阅读:Generative Adversarial Transformers

被校园暴力,性格内向的马斯克凄惨而励志的童年

The first in the industry! MOS sub evaluation model for subjective video quality experience that can run on mobile devices!

Relative path writing of files

爱普生L3153打印机如何清洗喷头

Object类,以及__new__,__init__,__setattr__,__dict__
随机推荐
[issue 21] face to face experience of golang engineer recruited by Zhihu Society
ETCD数据库源码分析——集群间网络层服务端RaftHandler
Embedded DSP audio development
【PaddleDetection】ModuleNotFoundError: No module named ‘paddle‘
Single page application (SPA) hash route and historical API route
Is Guotai Junan Securities reliable? Is it safe to open a securities account?
文件的相对路径写法
空闲中断无法清除
Win10 如何删除系统盘大文件hiberfil.sys
matlab习题 —— 符号运算相关练习
Yes, it's about water
Artifact for converting pcap to JSON file: joy (installation)
读书,使人内心宁静
Why is the service implementation class always red
Tips for visiting the website: you are not authorized to view the recovery method of this page
Basic operation of stack (implemented in C language)
GAMES104 作业2-ColorGrading
Use js programming questions [split] in Niuke
Inference optimization implementation of tensorrt model
What are the good practices of cloud cost optimization?