最便捷使用netty-websocket方法

1.pom添加依赖

<dependency>
<groupId>org.yeauty</groupId>
<artifactId>netty-websocket-spring-boot-starter</artifactId>
<version>0.8.0</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.41.Final</version>
</dependency>

2.工具类

package com.xck.service;

import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.timeout.IdleStateEvent; import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RestController;
import org.yeauty.annotation.*;
import org.yeauty.pojo.ParameterMap;
import org.yeauty.pojo.Session; import java.io.*;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet; @ServerEndpoint(prefix = "netty-websocket" ) //在yml文件配置参数
@RestController
@Scope("prototype")
public class NettyWebSocketUtil { /*// 注入的时候,给类的 service 注入
private static GpsService gpsService;
@Autowired
public void setChatService(GpsService gpsService) {
NettyWebSocketController.gpsService= gpsService;
}
*/ // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象
private static CopyOnWriteArraySet<Session> webSocketSet = new CopyOnWriteArraySet<Session>();
/**
* 请求连接
* @param session 请求连接的标识
* @param headers
* @param parameterMap 请求参数(nettyWS只能通过get方式传参数 URL?param="1"&param2="1")
* @throws IOException
*/
@OnOpen
public void onOpen(Session session, HttpHeaders headers,ParameterMap parameterMap) throws IOException {
webSocketSet.add(session);
String Parame=parameterMap.getParameter("Parame");
String Parame2=parameterMap.getParameter("Parame2");
}
/**
* 请求关闭
* @param session 请求连接的标识
* @throws IOException
*/
@OnClose
public void onClose(Session session) throws IOException {
// System.out.println("one connection closed");
webSocketSet.remove(session);
session.flush();
session.close(); }
/**
* 请求出错
* @param session 请求连接的标识
* @throws IOException
*/
@OnError
public void onError(Session session, Throwable throwable) {
webSocketSet.remove(session);
throwable.printStackTrace();
}
/**
* 接收数据
* @param session 请求连接的标识
* @param message 接收的消息
* @throws IOException
*/
@OnMessage
public void OnMessage(Session session, String message) { } /**
* 发送消息(二进制)
* @param session
* @param bytes
*/
@OnBinary
public void OnBinary(Session session, byte[] bytes) {
for (byte b : bytes) {
System.out.println(b);
}
session.sendBinary(bytes);
} /**
* 群发
* @param obj 发送的消息
*/
public static synchronized void sendMessage2(Object obj) {
//获取session
if (webSocketSet!=null) {
Iterator<Session> it = webSocketSet.iterator();
while (it.hasNext()) {
Session session = it.next();
if (session != null && session.isOpen()) {
session.sendText(obj.toString());
}else if(session != null && !session.isOpen()){
it.remove();
}
}
}
} @OnEvent
public void onEvent(Session session, Object evt) {
if (evt instanceof IdleStateEvent) {
IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
switch (idleStateEvent.state()) {
case READER_IDLE:
System.out.println("read idle");
break;
case WRITER_IDLE:
System.out.println("write idle");
break;
case ALL_IDLE:
System.out.println("all idle");
break;
default:
break;
}
}
}
}

3.配置文件(yml 文件)

netty-websocket:     #对应@ServerEndpoint(prefix = "netty-websocket" )
host: 0.0.0.0
path: /gps/WebSocket #访问路径
port: 8099 #端口

4.注册 (本地测试需要加入,打包发布注释掉)

@Configuration
public class WebConfig implements WebMvcConfigurer {
private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class); /**
* 功能描述(打war包时需要注释掉,打成war或者传统方式发布到tomcat中, 相当于启动了两次 )
* @author why
* @date 2019/6/10
* @param
* @return org.springframework.web.socket.server.standard.ServerEndpointExporter
* @description 配置ServerEndpointExporter,配置后会自动注册所有“@ServerEndpoint”注解声明的Websocket Endpoint
*/
/* @Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
*/ }

netty-websocket简单的使用方法的更多相关文章

  1. Netty+WebSocket简单实现网页聊天

    基于Netty+WebSocket的网页聊天简单实现 一.pom依赖 <dependency>        <groupId>io.netty</groupId> ...

  2. WebSocket简单介绍

    Java后端WebSocket的Tomcat实现 一.WebSocket简单介绍 随着互联网的发展,传统的HTTP协议已经很难满足Web应用日益复杂的需求了.近年来,随着HTML5的诞生,WebSoc ...

  3. HTTP协议系列(3)---包括WebSocket简单介绍

    一.HTTPS     HTTP是超文本传输协议,那HTTPS是什么尼?要明白HTTPS是什么先要明白HTTP的缺点,想一下我们在使用HTTP的时候会有那些缺点尼? 1.通信使用的明文(不加密),内容 ...

  4. netty的简单的应用例子

    一.简单的聊天室程序 public class ChatClient { public static void main(String[] args) throws InterruptedExcept ...

  5. websocket简单入门

    今天说起及时通信的时候,突然被问到时用推的方式,还是定时接受的方式,由于之前页面都是用传统的ajax处理,可能对ajax的定时获取根深蒂固了,所以一时之间没有相同怎么会出现推的方式呢?当被提及webs ...

  6. Netty+WebSocket 获取火币交易所数据项目

    Netty+WebSocket 获取火币交易所时时数据项目 先附上项目项目GitHub地址 spring-boot-netty-websocket-huobi 项目简介 本项目使用 SpringBoo ...

  7. Netty学习——基于netty实现简单的客户端聊天小程序

    Netty学习——基于netty实现简单的客户端聊天小程序 效果图,聊天程序展示 (TCP编程实现) 后端代码: package com.dawa.netty.chatexample; import ...

  8. netty websocket

    1 全局保存websocket的通道  NettyConfig.java public class NettyConfig { public static ChannelGroup group = n ...

  9. netty 实现简单的rpc调用

    yls 2020/5/23 netty 实现简单rpc准备 使用netty传输java bean对象,可以使用protobuf,也可以通过json转化 客户端要将调用的接口名称,方法名称,参数列表的类 ...

  10. CocoaPods 的简单快速安装方法

    CocoaPods 的简单快速安装方法(Setting up CocoaPods master repo 卡着不动,是因为淘宝镜像已经不能用了. 一.git clone方法安装cocoapods 镜像 ...

随机推荐

  1. vue中全局filter和局部filter怎么用?

    需求: 将价值上加上元单位符号(全局filter) <template> <div> 衣服价格:{{productPrice|formatTime}} </div> ...

  2. python 两个字典对比

    def commir_two_dict(dictone,dicttwo): pass_num=0 fail_num=0 try: for i in dictone.keys(): if i in di ...

  3. 2019软工实践_Alpha(2/6)

    队名:955 组长博客:https://www.cnblogs.com/cclong/p/11862633.html 作业博客:https://edu.cnblogs.com/campus/fzu/S ...

  4. Shell登陆远程服务器

    现场服务器较多,密码3个月过期,在到期时需更改密码. 使用expect编写,尝试登陆2次后退出(防止密码错误时账号锁定),超时重试一次. shell脚本调用并定时执行,登陆成功后执行一条命令,如:ho ...

  5. DNGuard HVM Unpacker(3.71 trial support and x64 fixed)

    DNGuard HVM Unpacker(3.71 trial support and x64 fixed) Gr8 news. Finally got the x64 crash fixed. DN ...

  6. openwrt共享打印机需要安装哪几个文件

    opkg updateopkg install luci-app-p910ndopkg install kmod-usb-printer

  7. TCP为什么会出现 RST

    就目前遇到的情况而言,都是负载设备,或健康检查设备发送的. 为什么会出现 RST 因为具有周期性,我大概猜到了,是 lvs 对我的后端服务的健康检查导致的,联系了网络运营服务客服人员,我把.pcap给 ...

  8. Manning Java Persistence with Hibernate & hibernate_in_action

    Manning | Java Persistence with Hibernatehttps://www.manning.com/books/java-persistence-with-hiberna ...

  9. Jenkins自动化版本构建

    1.拉取代码 2.更新父版本 更新依赖版本 3.打包并推送到maven私库 4.版本控制后提交代码并打成docker镜像 PS:修改pom.xml项目版本,这里我没使用插件,直接使用脚本进行修改,这样 ...

  10. ThreadPoolExecutor 定制线程池参数

    在 java 开发中经常需要执行一些“规格化”的任务,此时可以使用 java 线程池.节省创建线程时间,任务来时即可执行,高效. java 包是 java.util.concurrent .创建线程池 ...