netty-websocket简单的使用方法


最便捷使用netty-websocket方法

1.pom添加依赖


         org.yeauty
         netty-websocket-spring-boot-starter
         0.8.0


            io.netty
            netty-all
            4.1.41.Final

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 webSocketSet = new CopyOnWriteArraySet();
    /**
     * 请求连接
     * @param session  请求连接的标识
     * @param headers
     * @param parameterMap   请求参数(nettyWS只能通过get方式传参数   URL?param="1"¶m2="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 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();
    }
*/

}