Giter Club home page Giter Club logo

simplesocket's Introduction

simplesocket

一个简单的客户端 WebSocket 库。

快速开始

使用之前

simplesocket 约定与服务端使用 JSON 通信,JSON 格式如下

{
    "type":"",
    "data":{}
}

使用方法

引入 simplesocket

import SocketManager from 'simplesocket';

传入配置对象,获得 SocketManager 对象

const sm = new SocketManager(option);

以下是默认配置对象

{
    //连接协议,'ws' 或 'wss'
    protocol: 'ws',
    //连接的域名
    host: '',
    //连接的路径
    path: '',
    //连接时携带的 query 参数对象
    query: {},
    //完整的 url,有这个参数时会忽略以上配置项
    url: '',
    //最大尝试连接次数
    maxConnectCount: 5,
};

在需要的时候连接

const socket = sm.connect();

在需要的时候关闭连接

socket.close();

监听约定事件

//eventName 为约定的事件名,fn 为处理函数
socket.on(eventName,fn);

移除监听

//eventName 为约定的事件名,fn 为监听时的函数
socket.off(eventName,fn);

向服务器端发送消息

//eventName 为约定的事件名,data 为向服务器提交的数据
socket.emit(eventName,data);

simplesocket 的优势

  • 小。体积非常小
  • 原生。基于原生的 WebSocket 连接,可以和原生 WebSocket 并存
  • 简单。代码非常简单,任何开发者都能轻松阅读和定制
  • 无侵入。服务端无需增加任何库和插件

simplesocket's People

Contributors

starlight02 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.