guohongjin
2024-05-15 5b7639f0bd9e056738ec15100ed0532e965c6cd5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package cn.stylefeng.roses.kernel.socket.business.websocket.operator.channel;
 
import com.alibaba.fastjson.JSON;
import javax.websocket.Session;
import java.io.IOException;
 
/**
 * Socket操作类实现
 * <p>
 * 简单封装Spring Boot的默认WebSocket
 *
 * @author majianguo
 * @date 2021/6/1 下午3:41
 */
public class GunsSocketOperator implements SocketChannelExpandInterFace {
 
    /**
     * 实际操作的通道
     */
    private Session socketChannel;
 
    public GunsSocketOperator(Session socketChannel) {
        this.socketChannel = socketChannel;
    }
 
    @Override
    public void writeAndFlush(Object obj) {
        try {
            if (socketChannel.isOpen()) {
                socketChannel.getBasicRemote().sendText(JSON.toJSONString(obj));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public void writeToChannel(Object obj) {
        if (socketChannel.isOpen()) {
            socketChannel.getAsyncRemote().sendText(JSON.toJSONString(obj));
        }
    }
 
    @Override
    public void close() {
        try {
            if (socketChannel.isOpen()) {
                socketChannel.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public boolean isInvalid() {
        return socketChannel.isOpen();
    }
}