spring boot websocket

 1:在maven项目添加依赖

<dependency>  
           <groupId>org.springframework.boot</groupId>  
           <artifactId>spring-boot-starter-websocket</artifactId>  

       </dependency>


2:@Configuration 
public class WebCocketConfig {
@Bean  
    public ServerEndpointExporter serverEndpointExporter() {  
        return new ServerEndpointExporter();  
    } 

}

3:package com.efe.task.websocket;
import java.io.IOException;  
import java.util.concurrent.CopyOnWriteArraySet;  


import javax.websocket.OnClose;  
import javax.websocket.OnError;  
import javax.websocket.OnMessage;  
import javax.websocket.OnOpen;  
import javax.websocket.Session;  
import javax.websocket.server.ServerEndpoint;  


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


import com.efe.task.taskManager.taskExecuteClass.EbayAnalysisDataExecutor;
/**
 * @author    wenzuhuang
 * @date      2018年6月12日--下午3:44:44
 * @company   EFE
 * @project         task
 * @description  TODO
 */
 
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
private static Logger log = LoggerFactory
.getLogger(WebSocketServer.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。  
    private static int onlineCount = 0;  
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。  
   private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();  
  
    //与某个客户端的连接会话,需要通过它来给客户端发送数据  
    private Session session;  
  
    /** 
     * 连接建立成功调用的方法*/  
    @OnOpen  
    public void onOpen(Session session) {  
        this.session = session;  
        
        webSocketSet.add(this);     //加入set中  
        addOnlineCount();           //在线数加1  
        log.info("有新连接加入!当前在线人数为" + getOnlineCount());  
  
        
        try {  
             sendMessage("{'message':'来自客户端的消息:这是来自客户端的消息http://localhost:9998/Tue Jun 12 2018 15:59:58 GMT+0800 (中国标准时间)','date':'2018-06-12 15:59:58.925', 'level':'INFO',  'thread':'http-nio-9998-exec-9'}");  
        } catch (IOException e) {  
            log.error("websocket IO异常");  
        }  
    }  


    /** 
     * 连接关闭调用的方法 
     */  
    @OnClose  
    public void onClose() {  
        webSocketSet.remove(this);  //从set中删除  
        subOnlineCount();           //在线数减1  
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());  
    }  
  
    /** 
     * 收到客户端消息后调用的方法 
     * 
     * @param message 客户端发送过来的消息*/  
    @OnMessage  
    public void onMessage(String message, Session session) {  
        log.info("来自客户端的消息:" + message);  
  
        //群发消息  
        for (WebSocketServer item : webSocketSet) {  
            try {  
                item.sendMessage(message);  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
  
    /** 
     *  
     * @param session 
     * @param error 
     */  
    @OnError  
    public void onError(Session session, Throwable error) {  
        log.error("发生错误");  
        error.printStackTrace();  
    }  
  
  
    public void sendMessage(String message) throws IOException {  
        this.session.getBasicRemote().sendText(message);  
    }  
  
  
    /** 
     * 群发自定义消息 
     * */  
    public static void sendInfo(String message) throws IOException {  
        log.info(message);  
        for (WebSocketServer item : webSocketSet) {  
            try {  
                item.sendMessage(message);  
            } catch (IOException e) {  
                continue;  
            }  
        }  
    } 
  
    public static synchronized int getOnlineCount() {  
        return onlineCount;  
    }  
  
    public static synchronized void addOnlineCount() {  
        WebSocketServer.onlineCount++;  
    }  
  
    public static synchronized void subOnlineCount() {  
        WebSocketServer.onlineCount--;  
    }  

}


4:前端:

 


        $("#btnConnection").click(function() {
            //实现化WebSocket对象,指定要连接的服务器地址与端口
            socket = new WebSocket("ws://192.168.2.54:9998/websocket");
            //打开事件
            socket.onopen = function() {
                alert("Socket 已打开");
                //socket.send("这是来自客户端的消息" + location.href + new Date());
            };
            //获得消息事件
            socket.onmessage = function(msg) {
                alert(msg.data);
            };
            //关闭事件
            socket.onclose = function() {
                alert("Socket已关闭");
            };
            //发生了错误事件
            socket.onerror = function() {
                alert("发生了错误");
            }
        });
        
        //发送消息
        $("#btnSend").click(function() {
            socket.send("这是来自客户端的消息" + location.href + new Date());
        });
        
        //关闭
        $("#btnClose").click(function() {
            socket.close();
        });

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值