Springboot +WebSocket

一、pom.xml

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

二、WebSocketHandler

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
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.alibaba.fastjson.JSONObject;

@ServerEndpoint(value="/ws")
@Component
public class WebSocketHandler {
    
    protected Logger loger = LoggerFactory.getLogger(this.getClass());
    
    //当前连接数
     private static int onlineCount = 0;
     
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketHandler> webSocketSet = new CopyOnWriteArraySet<WebSocketHandler>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    
    @OnOpen
    public void onOpen(Session session) {
        
        this.session = session;
        webSocketSet.add(this);
        WebSocketHandler.onlineCount++;
        loger.info("new connect is opened,onlineCount="+onlineCount);
        try {
            
            Map<String, Object> msg = new HashMap<String, Object>();
            msg.put("type", "success");
            
            sendMessage(JSONObject.toJSONString(msg));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        WebSocketHandler.onlineCount--;
        loger.info("one connect is closed,onlineCount="+onlineCount);
    }
    
    @OnMessage
    public void onMessage(String message,Session session) {
        
        loger.info("receive msg:"+message);
    }
    
    @OnError
    public void onError(Session session,Throwable error) {
        
        loger.error("error:"+error.getMessage());
        error.printStackTrace();
    }
    
    public void sendMessage(String message) throws IOException{
        
        this.session.getBasicRemote().sendText(message);
    }
    
    public static void sendMessageToAll(String message) throws Exception{
        
        for(WebSocketHandler handler:webSocketSet) {
            
            try {
                handler.sendMessage(message);
            } catch (Exception e) {
                // TODO: handle exception
                
                continue;
            }
            
        }
        
    }
    
}

三、业务逻辑自己编写就行了。简单暴力。客户页面直接 websocket = new WebSocket (url)  websocket.server.url=ws://127.0.0.1:8080/ws 即可。

 

posted @ 2018-01-30 18:00  BBJB  阅读(299)  评论(1编辑  收藏  举报