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

边栏推荐
- el-form-item 正则验证
- A new book by teacher Zhang Yujin of Tsinghua University: 2D vision system and image technology (five copies will be sent at the end of the article)
- 【IoT毕设.上】STM32+机智云AIoT+实验室安全监控系统
- 使用 Lambda 函数URL + CloudFront 实现S3镜像回源
- [安网杯 2021] REV WP
- About fossage 2.0 "meta force meta universe system development logic scheme (details)
- 当你真的学会DataBinding后,你会发现“这玩意真香”!
- Build your own website (21)
- SWT/ANR问题--如何捕获性能的trace
- Scheme of printing statistical information in log
猜你喜欢

Learning to use livedata and ViewModel will make it easier for you to write business

App automation testing Kaiyuan platform appium runner

刘对(火线安全)-多云环境的风险发现

How can we protect our passwords?

QT社团管理系统

Open source internship experience sharing: openeuler software package reinforcement test

介绍一种对 SAP GUI 里的收藏夹事务码管理工具增强的实现方案

日志中打印统计信息的方案

使用 Lambda 函数URL + CloudFront 实现S3镜像回源

A new book by teacher Zhang Yujin of Tsinghua University: 2D vision system and image technology (five copies will be sent at the end of the article)
随机推荐
Scheme of printing statistical information in log
Explain IO multiplexing, select, poll, epoll in detail
刘对(火线安全)-多云环境的风险发现
Realize queue with stack and stack with queue (C language \leetcode\u 232+225)
SWT/ANR问题--当发送ANR/SWT时候如何打开binder trace(BinderTraces)
el-form-item 正则验证
Etcd summary mechanism and usage scenarios
SWT / anr problem - how to open binder trace (bindertraces) when sending anr / SWT
How to pass array parameters in get request
"National defense seven sons" funding soared, with Tsinghua reaching 36.2 billion yuan, ranking second with 10.1 billion yuan. The 2022 budget of national colleges and universities was made public
Use the npoi package of net core 6 C to read excel Pictures in xlsx cells and stored to the specified server
程序设计的基本概念
MySQL log
被裁三个月,面试到处碰壁,心态已经开始崩了
当主程架构游戏的时候,防止到处调用减少耦合性,怎么开放接口给其他人调用呢?
算网融合赋能行业转型,移动云点亮数智未来新路标
使用 Lambda 函数URL + CloudFront 实现S3镜像回源
App automation testing Kaiyuan platform appium runner
基于算力驱动、数据与功能协同的分布式动态(协同)渲染/功能运行时
8款最佳实践,保护你的 IaC 安全!