npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

websocket-encaps

v1.0.2

Published

WebSocket的封装和使用详细

Readme

websocket-encaps

一个轻量级、高可用的WebSocket封装工具包,支持自动重连、消息JSON解析、Token携带,适配原生JS、Vue、React等多场景。

🌟 核心功能

  • ✅ 自动重连:连接断开后按配置间隔重试,避免手动处理重连逻辑
  • ✅ Token携带:支持从Cookie获取Token,通过URL参数或子协议传递给服务器
  • ✅ 消息封装:自动序列化/反序列化JSON消息,兼容非JSON格式消息
  • ✅ 状态监听:暴露连接、消息、错误、关闭等回调,便于业务处理
  • ✅ 资源安全:手动关闭连接时自动清除定时器,避免内存泄漏

📦 安装

1. 安装核心包与依赖

本包依赖js-cookie获取Token,需同时安装:

# npm安装
npm install websocket-encaps js-cookie --save

# yarn安装(若用户使用yarn)
yarn add websocket-encaps js-cookie




⭐JavaScript
// 引入包
const WebSocketEncaps = require('websocket-encaps');
// 初始化连接
const ws = new WebSocketEncaps('ws://your-server-url');
// 监听连接成功
ws.on('open', () => {
  console.log('连接成功');
  // 发送消息
  ws.send('hello server');
});
// 监听收到消息
ws.on('message', (data) => {
  console.log('收到消息:', data);
});
// 监听错误
ws.on('error', (err) => {
  console.error('错误:', err);
});
// 监听关闭
ws.on('close', () => {
  console.log('连接关闭');
});




⭐Vue2
<script>
// 引入你的包
import { connectSocket, closeSocket, socketSend } from 'websocket-encaps';
export default {
    name: 'WebSocketEncaps',
    data() {
        return {
            testParams: {
                id: 1,
                name: "test"
            },
            testList: []
        };
    },
    beforeDestroy() {
        # // 页面销毁时关闭Socket
        closeSocket();
    },
    created() {
        this.firstInitSocket(); //调用方法,初始化socket
    },
    methods: {
        # // ⭐ 1使用环境变量
        # // VUE_APP_DEV_WEBSOCKET_URL = 'ws://IP:9013/websocket/xx/xx'
        # // 实时数据,这里没有第二个参数data,只有参数1_URL和参数3_数据函数
        firstInitSocket() {
            connectSocket(
                process.env.VUE_APP_DEV_WEBSOCKET_URL,
                this.handleMessage,
            );
        },
        # 或者
        # // ⭐ 2直接使用地址
        # // 定义websocket方法 , 方便调用 ,在方法里面初始化websocket
        firstInitSocket() {
            # //参数:1、路径,  2、实参, 3、函数调用,
            connectSocket(
                `ws://192.168.0.29:8080/....../real?`,
                "id=" +
                this.testParams.id +
                "&bus=" +
                this.testParams.name,
                this.handleMessage,
            );
        },
        # // 定义函数方法,方便调用
        handleMessage(e) {
            console.log("后端返回的数据:",e);
            if (e?.data === "Success") {
                // console.log(123)
                // console.log(e.data)
                this.$globalMessage = this.$message({
                    message: "test", 
                    type: "success", 
                    center: true, 
                    offset: 400, 
                    duration: 6000, 
                    showClose: true,
                });
            } else if (e?.data) {

                # // console.log(456)
                # // console.log(e.data)
                try {
                   const data = e.data; 
                   # // 这里没有转换数据,记得转换
                   #  const data = JSON.parse(e.data); 
                   # // console.log(data, 789)
                   this.testList = data
                   # // console.log(this.testList , 0)
                } catch (error) {
                    console.error("JSON解析失败:", error);
                    return;
                }

            }  else {
                this.$globalMessage = this.$message({
                    message: "请求失败", 
                    type: "error", 
                    center: true, 
                    offset: 400,
                    duration: 2000,
                    showClose: true,
                });
            }
        },
    },
};
</script>