当前位置:网站首页>WebSocket(简单体验版)
WebSocket(简单体验版)
2022-07-01 14:03: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')
}

边栏推荐
- Play with grpc - communication between different programming languages
- 【Flask】Flask启程与实现一个基于Flask的最小应用程序
- 04 redis source code data structure dictionary
- 【NLP】预训练模型——GPT1
- Play with mongodb - build a mongodb cluster
- [NLP] pre training model - gpt1
- 那个很努力的学生,高考失败了……别慌!你还有一次逆袭机会!
- Après avoir été licencié pendant trois mois, l'entrevue s'est effondrée et l'état d'esprit a commencé à s'effondrer.
- 【剑指 Offer】55 - II. 平衡二叉树
- Applet - multiple text line breaks in view
猜你喜欢

QT社团管理系统

2022 PMP project management examination agile knowledge points (6)

leetcode622. Design cycle queue (C language)

被裁三個月,面試到處碰壁,心態已經開始崩了

开源者的自我修养|为 ShardingSphere 贡献了千万行代码的程序员,后来当了 CEO

SAP intelligent robot process automation (IRPA) solution sharing

被裁三个月,面试到处碰壁,心态已经开始崩了

当你真的学会DataBinding后,你会发现“这玩意真香”!
![[machine learning] VAE variational self encoder learning notes](/img/38/3eb8d9078b2dcbe780430abb15edcb.png)
[machine learning] VAE variational self encoder learning notes

Liu Dui (fire line safety) - risk discovery in cloudy environment
随机推荐
玩转MongoDB—搭建MongoDB集群
Leetcode question 1: sum of two numbers (3 languages)
Benefiting from the Internet, the scientific and technological performance of overseas exchange volume has returned to high growth
What class loading mechanisms does the JVM have?
Sign APK with command line
程序设计的基本概念
TexStudio使用教程
学会使用LiveData和ViewModel,我相信会让你在写业务时变得轻松
So programmers make so much money doing private work? It's really delicious
QT社团管理系统
2022 PMP project management examination agile knowledge points (6)
玩转gRPC—不同编程语言间通信
SWT/ANR问题--当发送ANR/SWT时候如何打开binder trace(BinderTraces)
一文读懂TDengine的窗口查询功能
【商业终端仿真解决方案】上海道宁为您带来Georgia介绍、试用、教程
[flask] flask starts and implements a minimal application based on flask
当你真的学会DataBinding后,你会发现“这玩意真香”!
建立自己的网站(21)
【IoT毕设.下】STM32+机智云AIoT+实验室安全监控系统
Introduction to distributed transactions (Seata)