当前位置:网站首页>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')
}

边栏推荐
- 基于算力驱动、数据与功能协同的分布式动态(协同)渲染/功能运行时
- What class loading mechanisms does the JVM have?
- 使用 Lambda 函数URL + CloudFront 实现S3镜像回源
- 8 best practices to protect your IAC security!
- 【IoT毕设.上】STM32+机智云AIoT+实验室安全监控系统
- Build your own website (21)
- 当主程架构游戏的时候,防止到处调用减少耦合性,怎么开放接口给其他人调用呢?
- SAP intelligent robot process automation (IRPA) solution sharing
- Effet halo - qui dit qu'il y a de la lumière sur la tête est un héros
- TDengine 连接器上线 Google Data Studio 应用商店
猜你喜欢

【修复版】仿我爱看电影网站模板/海洋CMS影视系统模板

【IoT毕设.上】STM32+机智云AIoT+实验室安全监控系统

Fiori applications are shared through the enhancement of adaptation project
![[安网杯 2021] REV WP](/img/98/ea5c241e2b8f3ae4c76e1c75c9e0d1.png)
[安网杯 2021] REV WP

Après avoir été licencié pendant trois mois, l'entrevue s'est effondrée et l'état d'esprit a commencé à s'effondrer.

那个很努力的学生,高考失败了……别慌!你还有一次逆袭机会!

开源实习经验分享:openEuler软件包加固测试

How will the surging tide of digitalization overturn the future?

2022年PMP项目管理考试敏捷知识点(6)
![[IOT completion. Part 2] stm32+ smart cloud aiot+ laboratory security monitoring system](/img/b2/e8f81ecda6f5f4fc65501aaf9f13cf.gif)
[IOT completion. Part 2] stm32+ smart cloud aiot+ laboratory security monitoring system
随机推荐
04 redis source code data structure dictionary
MySQL日志
Use the npoi package of net core 6 C to read excel Pictures in xlsx cells and stored to the specified server
程序设计的基本概念
C language ordering management system
The integration of computing and Internet enables the transformation of the industry, and the mobile cloud lights up a new roadmap for the future of digital intelligence
Solution to 0xc000007b error when running the game [easy to understand]
App automation testing Kaiyuan platform appium runner
Basic operation of queue (implemented in C language)
[IOT completion. Part 2] stm32+ smart cloud aiot+ laboratory security monitoring system
How will the surging tide of digitalization overturn the future?
2022. Let me take you from getting started to mastering jetpack architecture components - lifecycle
Fiori 应用通过 Adaptation Project 的增强方式分享
Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
【Flask】Flask启程与实现一个基于Flask的最小应用程序
Build your own website (21)
Applet - multiple text line breaks in view
一文读懂TDengine的窗口查询功能
Station B was scolded on the hot search..
[Jianzhi offer] 55 - ii balanced binary tree