A simple, fast integration of WebSocket spring-stater

Overview

websocket-spring-boot-starter

readme

介绍

一个简单,快速,低配的spring-boot-starter,是对spring-boot-starter-websocket的扩展与二次封装,简化了springboot应用对websocket的操作

特点

  1. 简单,低配
  2. 支持websocket连接可控,可以防止前端恶意连接,重复连接
  3. 支持单点发送,部分发送,所有发送
  4. 支持消息中转,集群环境跨机器传递消息(redis 做的消息中转,需要配置redis)
  5. 可监控实时连接数

安装教程

  1. 先把项目下载到本地
git clone [email protected]:Jack9610/websocket-spring-boot-starter.git
  1. 将项目install到本地
maven install 
  1. 依赖进自己的项目
        <dependency>
            <groupId>com.jackgroupId>
            <artifactId>websocket-spring-boot-starterartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>

使用说明

  1. 实现 Identity ,这个接口是对当前使用websocket对象的抽象,建议使用当前系统登录的user,只需要返回一个唯一的IdentityId即可
@Data
public class User implements Identity {

    private String userId;

    private String username;

    private String password;

    @Override
    public String getIdentityId() {
        // 可以自定义返回任何信息,确保每个客户端唯一即可
        return userId;
    }
}
  1. 实现 IdentityService,这个接口提供返回Identity的服务,这里返回的Identity将作用于鉴定是否连接,接收消息的MessageHandler的入参
@Service
public class IdentityServiceImpl implements IdentityService {

    @Resource
    private UserService userService;

    @Override
    public Identity getIdentity(String s) {
        String userId = JwtUtil.getUserId(s);
        // 这里演示,从数据库直接读出user
        return userService.get(userId);
    }
}
  1. 发消息
public class BizService{
    
    @Autowired
    private WsTemplate wsTemplate;

    public void test(){
//        wsTemplate.sendMessageToAll(...);
//        wsTemplate.sendMessageToPart(...);
//        wsTemplate.sendMessageToSingle(...);
    }
}
  1. 收消息
{ // 处理前端发送的消息 @Override public void handleMessage(TestParam testparam,Identity identity){ // do Something } // 定义一个场景 @Override public String getScene(){ return "test"; } }">
// TestParam 只是一个普通的JavaBean,自己定义的,前端在这个Scene下,必须传该javabean对应的json格式数据字符串
// 前端发送数据示例: {"scene":"test","data":{"name":"Jack","description":"一只菜鸟"}}
public class HalloMessageHandler implements MessageHandler<TestParam>{
    
     // 处理前端发送的消息
    @Override
    public void handleMessage(TestParam testparam,Identity identity){
       // do Something
    }
    
    // 定义一个场景
    @Override
    public String getScene(){
        return "test";
    }
}

测试html

菜鸟教程(runoob.com)
">
>
<html>
<head>
    <meta charset="utf-8">
    <title>菜鸟教程(runoob.com)title>
head>
<style>
    .box{
        border: 1px solid red;
        width: 1000px;
        height: 600px;
        overflow-y: auto;
    }

style>
<body>
<div class="box">
div>
<input type="text" id="input">
<button id="send">发消息button>
<button id="end">结束button> body> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js">script> <script type="text/javascript"> // 发送消息参数示例 : {"scene":"test","data":{"name":"Jack","description":"一只菜鸟"}} // 连接参数 : ws://ip:port/ws?Authorization={{授权信息}} var ws = new WebSocket("ws://127.0.0.1:8000/ws?Authorization=abc"); ws.onopen = function(){ // Web Socket 已连接上,使用 send() 方法发送数据 alert("连接成功..."); }; ws.onclose = function(e){ // 关闭 websocket alert("连接已关闭..."+ e.status + " " + e.reason); }; ws.onmessage = function (evt) { var received_msg = evt.data; $(".box").append('收到:' + received_msg + '
'
); }; ws.onerror = function (evt) { var received_msg = evt.data; alert("error" + received_msg) $(".box").append(received_msg + '
'
); }; $('#send').click(function(){ $(".box").append($('#input').val() + '
'
); ws.send($('#input').val()); $('#input').val('') }) $('#end').click(function(){ ws.close() }) self.setInterval("send()",10000); function send() { $(".box").append('发送:ping' + '
'
); ws.send("ping") } script> html>
You might also like...

A simple Discord bot, which shows the server status of the Lost Ark server Beatrice

A simple Discord bot, which shows the server status of the Lost Ark server Beatrice

Beatrice A simple Discord bot, which shows the server status of the Lost Ark server Beatrice. Example Usage Clone the repository. Edit the property fi

Mar 9, 2022

A simple Socket program with GUI.

Socket A simple Socket program with GUI (by using swing). Suggest to open the folder 'Socket'(TCP) or 'SocketUDP' with IDEA There're 2 methods to run

Sep 21, 2022

Spring Integration provides an extension of the Spring programming model to support the well-known Enterprise Integration Patterns (EIP)

Spring Integration Code of Conduct Please see our Code of conduct. Reporting Security Vulnerabilities Please see our Security policy. Checking out and

Dec 30, 2022

A distributed data integration framework that simplifies common aspects of big data integration such as data ingestion, replication, organization and lifecycle management for both streaming and batch data ecosystems.

Apache Gobblin Apache Gobblin is a highly scalable data management solution for structured and byte-oriented data in heterogeneous data ecosystems. Ca

Jan 4, 2023

Docker-compose-integration-tstst - An exploration of how to run integration tests against an application that has inconvenient external dependencies (e.g. a SQL database).

Tstst? it was supposed to be docker-compose-integration-tests but i was too lazy to fix it at the outset, and now im trying to convince myself its fun

Jan 4, 2022

Framework for automated integration tests with focus on messaging integration

Citrus Integration Testing Welcome to Citrus Citrus is a test framework written in Java that is able to create fully automated end-to-end use case tes

Dec 27, 2022

循序渐进,学习Spring Boot、Spring Boot & Shiro、Spring Batch、Spring Cloud、Spring Cloud Alibaba、Spring Security & Spring Security OAuth2,博客Spring系列源码:https://mrbird.cc

Spring 系列教程 该仓库为个人博客https://mrbird.cc中Spring系列源码,包含Spring Boot、Spring Boot & Shiro、Spring Cloud,Spring Boot & Spring Security & Spring Security OAuth2

Jan 6, 2023

Flexible framework for workflow and decision automation with BPMN and DMN. Integration with Spring, Spring Boot, CDI.

Camunda Platform - The open source BPMN platform Camunda Platform is a flexible framework for workflow and process automation. It's core is a native B

Dec 30, 2022

An integration solution for Spring Cloud and Tencent middleware - Spring Cloud和腾讯中间件的集成方案

Spring Cloud Tencent English | 简体中文 Introduction Spring Cloud Tencent contains components distributed micro-service applications need during developin

Dec 29, 2022

Hi, Spring fans! In this installment we look Spring Integration's support for MQTT and the HiveMQ broker

Spring Integration MQTT & HiveMQ Hi, Spring fans! In this installment we look Spring Integration's support for MQTT and the HiveMQ broker. I'm joined

Nov 21, 2022

Fast and Easy mapping from database and csv to POJO. A java micro ORM, lightweight alternative to iBatis and Hibernate. Fast Csv Parser and Csv Mapper

Simple Flat Mapper Release Notes Getting Started Docs Building it The build is using Maven. git clone https://github.com/arnaudroger/SimpleFlatMapper.

Dec 17, 2022

You are looking for examples, code snippets, sample applications for Spring Integration? This is the place.

Spring Integration Samples Note This (master) branch requires Spring Integration 5.0 or above. For samples running against earlier versions of Spring

Dec 30, 2022

Spring Boot OAuth 2.0 Client Implementation + MySQL Integration

Spring Boot OAuth 2.0 Client Implementation + MySQL Integration

Spring Boot OAuth 2.0 Client + MySQL 1. What is OAuth 2.0 ? The OAuth 2.0 authorization framework enables a third-party application to obtain limited

May 12, 2022

Kafka integration with Java Spring-boot: producer-consumer model

Kafka integration with Java Spring-boot with one application serving as a producer and the other consuming the messages

Apr 26, 2022

This module explains about the example of Spring MVC + Database Integration with MySQL using Hibernate ORM with practical coding example and required JAR dependencies

SpringMVC-Database-Integration This module explains about the example of Spring MVC + Database Integration with MySQL using Hibernate ORM with practic

Nov 2, 2021

Asynchronous Http and WebSocket Client library for Java

Async Http Client Follow @AsyncHttpClient on Twitter. The AsyncHttpClient (AHC) library allows Java applications to easily execute HTTP requests and a

Jan 8, 2023
Owner
Jack
Jack
Magician is an asynchronous non-blocking network protocol analysis package, supports TCP, UDP protocol, built-in Http, WebSocket decoder

An asynchronous non-blocking network protocol analysis package Project Description Magician is an asynchronous non-blocking network protocol analysis

贝克街的天才 103 Nov 30, 2022
A barebones WebSocket client and server implementation written in 100% Java.

Java WebSockets This repository contains a barebones WebSocket server and client implementation written in 100% Java. The underlying classes are imple

Nathan Rajlich 9.5k Dec 30, 2022
A Java event based WebSocket and HTTP server

Webbit - A Java event based WebSocket and HTTP server Getting it Prebuilt JARs are available from the central Maven repository or the Sonatype Maven r

null 808 Dec 23, 2022
WebSocket server with creatable/joinable channels.

bytesocks ?? bytesocks is a WebSocket server which allows clients to create "channels" and send messages in them. It's effectively an add-on for byteb

lucko 6 Nov 29, 2022
Distributed WebSocket Server

Keeper 分布式 WebSocket 服务器。 注意事项 IO 线程和业务线程分离:对于小业务,依旧放到 worker 线程中处理,对于需要和中间件交互的丢到业务线程池处理,避免 worker 阻塞。 WebSocket 握手阶段支持参数列表。 插件 本服务功能插件化。

岚 1 Dec 15, 2022
Microhttp - a fast, scalable, event-driven, self-contained Java web server

Microhttp is a fast, scalable, event-driven, self-contained Java web server that is small enough for a programmer to understand and reason about.

Elliot Barlas 450 Dec 23, 2022
Simple & Lightweight Netty packet library + event system

Minimalistic Netty-Packet library Create packets with ease Bind events to packets Example Packet: public class TestPacket extends Packet { privat

Pierre Maurice Schwang 17 Dec 7, 2022
A simple multiplayer game

PixelExplorer Versions v0.0.1 : Play nothing together :) - 17/May/2021 So far we just have a basic echo server. How we did this was We build a new pro

Heath L Campbell 4 Jun 14, 2021
A simple minecraft mod for 1.12.2 which logs sent and received packets.

Packet-Logger A simple minecraft mod for 1.12.2 which logs sent and received packets. Usage You must have Forge 1.12.2 installed. Download the jar fro

null 14 Dec 2, 2022
A simple proxy software made for Telegram. Works well for areas that have MTProxy or Socks5 blocked.

A simple proxy software made for Telegram. Works well for areas that have MTProxy or Socks5 blocked.

null 42 Dec 19, 2022