springboot+websocket客户端和服务端

  • websocket简介

    WebSocket协议本质上是一个基于TCP的协议,它由通信协议和编程API组成,WebSocket能够在浏览器和服务器之间建立双向连接,以基于事件的方式,赋予浏览器实时通信能力。既然是双向通信,就意味着服务器端和客户端可以同时发送并响应请求,而不再像HTTP的请求和响应。
            在WebSocket出现之前,很多网站为了实现实时推送技术,通常采用的方案是轮询(Polling)和Comet技术,Comet又可细分为两种实现方式,一种是长轮询机制,一种称为流技术,这两种方式实际上是对轮询技术的改进,这些方案带来很明显的缺点,需要由浏览器对服务器发出HTTP request,大量消耗服务器带宽和资源。面对这种状况,HTML5定义了WebSocket协议,能更好的节省服务器资源和带宽并实现真正意义上的实时推送。

  • 应用场景

Web领域的实时推送技术,也被称作Realtime技术。这种技术要达到的目的是让用户不需要刷新浏览器就可以获得实时更新。它有着广泛的应用场景,比如在线聊天室、在线客服系统、评论系统、WebIM等。


  • springboot框架下websocket客户端和服务端实现

  1. 依赖导入

      org.springframework.boot
      spring-boot-starter-websocket
  2. WebSocketConfig
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    
    @Configuration
    public class WebSocketConfig {
    
        /**
         * ServerEndpointExporter 作用
         * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
         *
         * @return
         */
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    }
    说明:该配置类很简单,通过这个配置springboot才回去扫描websocket的注解。
  3. websocket服务端
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Component;
    
    import javax.websocket.OnClose;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.PathParam;
    import javax.websocket.server.ServerEndpoint;
    import java.util.concurrent.ConcurrentHashMap;
    
    
    /**
     * @ServerEndpoint 这个注解有什么作用?
     * 

    * 这个注解用于标识作用在类上,它的主要功能是把当前类标识成一个WebSocket的服务端 * 注解的值用户客户端连接访问的URL地址 */ @Slf4j @Component @ServerEndpoint("/websocket/{name}") public class SocketServer { /** * 用于存所有的连接服务的客户端,这个对象存储是安全的 */ private static ConcurrentHashMap webSocketSet = new ConcurrentHashMap<>(); /** * 与某个客户端的连接对话,需要通过它来给客户端发送消息 */ private Session session; /** * 标识当前连接客户端的用户名 */ private String name; @OnOpen public void OnOpen(Session session, @PathParam(value = "name") String name) { this.session = session; this.name = name; // name是用来表示唯一客户端,如果需要指定发送,需要指定发送通过name来区分 webSocketSet.put(name, this); log.info("[WebSocket] 连接成功,当前连接人数为:={}", webSocketSet.size()); } @OnClose public void OnClose() { webSocketSet.remove(this.name); log.info("[WebSocket] 退出成功,当前连接人数为:={}", webSocketSet.size()); } @OnMessage public void OnMessage(String message) { log.info("[WebSocket] 收到消息:{}", message); //判断是否需要指定发送,具体规则自定义 if (message.indexOf("TOUSER") == 0) { String name = message.substring(message.indexOf("TOUSER") + 6, message.indexOf(";")); AppointSending(name, message.substring(message.indexOf(";") + 1, message.length())); } else { GroupSending(message); } } /** * 群发 * * @param message */ public void GroupSending(String message) { for (String name : webSocketSet.keySet()) { try { webSocketSet.get(name).session.getBasicRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } } /** * 指定发送 * * @param name * @param message */ public void AppointSending(String name, String message) { try { webSocketSet.get(name).session.getBasicRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } }

    说明:@ServerEndpoint("/websocket/{name}")注明该类是websocket的服务端,参数表明访问地址。
  4. websocket客户端
    import lombok.extern.slf4j.Slf4j;
    
    import javax.websocket.*;
    
    @Slf4j
    @ClientEndpoint
    public class SocketClient {
    
        @OnOpen
        public void onOpen() {
            log.info("webSocket on onOpen------");
        }
    
        @OnMessage
        public void onMessage(String message) {
    
            log.info("message:{}",message);
        }
    
        @OnClose
        public void onClose(Session session, CloseReason reason) {
            log.info("断线重连:{}",reason.toString());
    
        }
    
        @OnError
        public void onError(Throwable ex) {
            log.error("ex:{}", ex);
        }
    
    }
    说明:@ClientEndpoint标识是websocket客户端,实现@OnOpen,@OnMessage,@OnClose,@OnError四个方法。
    @OnOpen 当 websocket 建立连接成功后,会触发这个注解修饰的方法
    @OnMessage 当websocket接收到消息,会触发这个注解修改的方法
    @OnClose 当 websocket 建立的连接断开后,会触发这个注解修饰的方法。CloseReason对象可以获取到断开连接的原因和错误码
    @OnError 当 websocket 建立连接时出现异常会触发这个注解修饰的方法
  5. 客户端发送消息
        public static void main(String[] args) {
            URI path = URI.create("ws://localhost:8080/websocket/");
            WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
    
            Session session = null;
            SocketClient socketClient = new SocketClient();
            try {
                session = webSocketContainer.connectToServer(socketClient, path);
            }catch (Exception e) {
                log.error("sendMsg error:{}", e);
            }
            session.getAsyncRemote().sendText("msg");
        }

    参考以上代码通过 session.getAsyncRemote().sendText("msg");的方式发送消息。path参数填入自己websocket服务端的路径。

参考:
http://www.bubuko.com/infodetail-3254804.html

 

你可能感兴趣的:(java)