WebSocketServer.java 2.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
package com.kwan.springbootkwan.service;

import org.springframework.stereotype.Component;

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 java.io.IOException;
12 13
import java.text.SimpleDateFormat;
import java.util.Date;
14 15 16
import java.util.concurrent.CopyOnWriteArraySet;

@Component
17
@ServerEndpoint("/websocket")
18
public class WebSocketServer {
19 20
    //准备一个内部安全的集合 存放所有用户的websocket服务
    private static CopyOnWriteArraySet<WebSocketServer> wsset = new CopyOnWriteArraySet<>();
21 22 23
    private Session session;

    @OnOpen
24
    public void opOpen(Session session) {
25
        this.session = session;
26 27 28 29
        //将自身填充到set集合中 这个集合是所有客户端websocket的集合

        wsset.add(this);
//        sendMsg();
30 31 32 33


    }

34 35 36 37
    @OnClose
    public void onClose() {
        //将自己从set集合中删除
        wsset.remove(this);
38 39 40 41
    }

    @OnError
    public void onError(Session session, Throwable error) {
42
        System.out.println(this + "发生错误了");
43 44
    }

45 46 47 48 49 50
    //客户端发来消息
    @OnMessage
    public void onMessage(String clientMsg, Session session) {
        System.out.println("来自客户端的信息+“。。。。。。。。。”===》" + clientMsg);
        //每隔一秒给你推送一条当前时间信息
        sendAllClient(clientMsg);
51 52
    }

53 54 55 56 57 58 59 60
    private void sendMsg() {
        try {
            while (true) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = sdf.format(new Date());
                //发送数据
                this.session.getBasicRemote().sendText(time);
                Thread.sleep(1000);
61
            }
62 63 64 65
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
66 67 68
        }
    }

69 70 71 72 73 74 75 76
    private void sendAllClient(String msg) {
        try {
            for (WebSocketServer wss : wsset) {
                wss.session.getBasicRemote().sendText(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
77
    }
78
}