whyclj
2020-04-25 1851839aa296e8ce8a5ce1846296820c449f9987
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package com.fgkj.services;
 
/*
 * Copyright © reserved by roomdis.com, service for tgn company whose important business is rural e-commerce.
 */
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
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.apache.log4j.Logger;
import org.springframework.web.context.ContextLoader;
 
import com.google.gson.Gson;
 
 
/**
 * @author shihuc
 * @date 2017年8月22日 下午2:20:18
 */
@ServerEndpoint("/websocket")
public class WebsocketService {
    
    private static Logger logger = Logger.getLogger(WebsocketService.class);
    
    //private HttpSendService httpSendService;
    
    private String videoRecServerHost = "10.90.7.10";
    
    private int videoRecServerPort = 7667;
    
    /*
     * 当存在多个客户端访问时,为了保证会话继续保持,将连接缓存。
     */
    private static Map<String, WebsocketService> webSocketMap = new ConcurrentHashMap<String, WebsocketService>();
    private Session session;
    
    private static final WebsocketService instance = new WebsocketService();
 
    public static final WebsocketService getInstance() {
        return instance;
    }
 
    @OnMessage
    public void onTextMessage(String message, Session session) throws IOException, InterruptedException {
 
        // Print the client message for testing purposes
        logger.info("Received: " + message);
        //TODO: 调用接口将消息发送给客户端后台服务系统
        Gson gson = new Gson();
        //KefuMessage kfMsg = gson.fromJson(message, KefuMessage.class);
        //httpSendService = ContextLoader.getCurrentWebApplicationContext().getBean(HttpSendService.class);
    }
    
    /**
     * 主要用来接受二进制数据。
     * 
     * @author shihuc
     * @param message
     * @param session
     * @throws IOException
     * @throws InterruptedException
     */
    @OnMessage
    public void onBinaryMessage(ByteBuffer message, Session session, boolean last) throws IOException, InterruptedException {
        byte [] sentBuf = message.array();
        
        logger.info("Binary Received: " + sentBuf.length + ", last: " + last);
        
        //下面的代码逻辑,是用UDP协议发送视频流数据到视频处理服务器做后续逻辑处理
        //sendToVideoRecognizer(sentBuf);
    }
 
    /**
     * @author shihuc
     * @param sentBuf
     * @throws SocketException
     * @throws UnknownHostException
     * @throws IOException
     */
    private void sendToVideoRecognizer(byte[] sentBuf) throws SocketException, UnknownHostException, IOException {
        DatagramSocket client = new DatagramSocket();
        InetAddress addr = InetAddress.getByName(videoRecServerHost);
        DatagramPacket sendPacket = new DatagramPacket(sentBuf, sentBuf.length, addr, videoRecServerPort);
        client.send(sendPacket);
        client.close();
    }
 
//    @OnOpen
//    public void onOpen(Session session){
//        this.session = session;
//        String staffId = session.getQueryString();        
//        webSocketMap.put(staffId, this);
//        logger.info(staffId + " client opened");
//    }
    
    @OnOpen
    public void onOpen(Session session){
        logger.info("client opened: " + session.toString());
    }
 
    @OnClose
    public void onClose() {
        logger.info("client onclose");        
    }
    
    @OnError
    public void onError(Session session, Throwable error){
        logger.info("connection onError");
        logger.info(error.getCause());
    }
    
    public boolean sendMessage(String message, String staffId) throws IOException{
        WebsocketService client = webSocketMap.get(staffId);
        if (client == null) {
            return false;
        }
        boolean result=false;
        try {            
            client.session.getBasicRemote().sendText(message);
            result=true;
        } catch (IOException e) {
            try {
                client.session.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return result;
    }
}