Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

websocket-front

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

websocket-front

WebSocket client for browser with reconnect and heartbeat

  • 1.0.3
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2
decreased by-50%
Maintainers
1
Weekly downloads
 
Created
Source

websocket-front

前端对原生 WebSocket 的封装,默认支持自动重连,支持心跳检测

技术栈

typescript + rollup

安装

yarn add websocket-front

# 或

npm install websocket-front

使用

最简单的连接:支持自动重连,支持心跳检测

import Socket from 'websocket-front';
const socket = new Socket('ws://127.0.0.1:3001')

配置项

import Socket from 'websocket-front';
const socket = new Socket('ws://127.0.0.1:3001', {
  // 重连
  isReconnect: true,
  reconnectTimeout: 300,
  reconnectRepeat: 5,
  // 心跳检测
  isHeartbeat: true
  pingMsg: JSON.stringify({
          messageType: "0",
          content: "ping",
        }),
  pingTimeout: 300,
  pongTimeout: 300,
  // 回调
  onMessage: receiveMessage,
  onError: errorCallback,
  close: closeCallback,
})
const receiveMessage = (message: Event) => {
  console.log('接收到的消息:', message)
}
const errorCallback = (error: Event) => {
  console.log('错误信息', event)
}
const closeCallback = (event: Event) => {
  console.log('关闭了')
}

方法

import Socket from 'websocket-front';
const socket = new Socket('ws://127.0.0.1:3001')

// 执行某些操作
socket.sendMessage('发送WebSocket消息');

// 执行某些操作
socket.close()

API

第一个参数

名称类型描述默认值
urlstringwebsocket 地址

第二个参数对象

名称类型描述默认值
isReconnectboolean是否需要自动重连true
reconnectTimeoutnumber自动重连间隔时间300ms
reconnectRepeatnumber尝试自动重连的次数Infinity
isHeartbeatboolean是否支持心跳检测
pingMsgstring心跳检测发送给后端的消息'ping'
pingTimeoutnumber发送心跳检测消息的延迟时间30s
pongTimeoutnumber多长时间没有收到返回的心跳就重启300ms

事件

名称类型描述默认值
onMessage(event:Event) => void收到后端返回的消息后的回调
onError(error: Event) => void收到错误信息后的回调
close(event: Event) => voidWebSocket 关闭了的回调

方法

事件名称说明回调函数
sendMessage向后端发送消息
close关闭 WebSocket

Keywords

FAQs

Package last updated on 15 Aug 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc