shikeying
2024-02-23 1d6e7763f4a30272cc0818ea12f83697b7375c45
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.iplatform.tcp;
 
import com.walker.infrastructure.utils.JsonUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
 
public class DemoWebsocketClient extends WebSocketClient {
 
    protected final transient Logger logger = LoggerFactory.getLogger(this.getClass());
 
    public DemoWebsocketClient(URI serverUri) {
        super(serverUri);
    }
 
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
//        logger.info("ws 连接成功");
        String data = null;
        Map<String, String> map = new HashMap<>(4);
        map.put("protocol", "login");
        map.put("uid", this.uid);
        try {
            data = JsonUtils.objectToJsonString(map);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        this.send(data);
        logger.info("客户端发送登录请求,name = {}", this.uid);
    }
 
    @Override
    public void onMessage(String s) {
        if(s.indexOf("heartbeat") >= 0){
            return;
        }
        logger.info("ws 收到消息:{}", s);
        try {
            DemoLoginResponse response = JsonUtils.jsonStringToObject(s, DemoLoginResponse.class);
            if(response.getProtocol().equals("login")){
                logger.info("websocket 登录成功:{}", response.getUid());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
    @Override
    public void onClose(int i, String s, boolean b) {
        logger.warn("连接被关闭:code={}, reason={}, remote={}", i, s, b);
    }
 
    @Override
    public void onError(Exception e) {
        logger.error("连接错误:" + e.getMessage(), e);
    }
 
    public String getUid() {
        return uid;
    }
 
    public void setUid(String uid) {
        this.uid = uid;
    }
 
    public String getUserName() {
        return userName;
    }
 
    public void setUserName(String userName) {
        this.userName = userName;
    }
 
    private String uid;
    private String userName;
}