|
6 | 6 | import java.io.IOException; |
7 | 7 | import java.net.URI; |
8 | 8 | import java.net.URISyntaxException; |
9 | | -import java.util.concurrent.ScheduledExecutorService; |
10 | | -import java.util.concurrent.ScheduledFuture; |
11 | | -import java.util.concurrent.TimeUnit; |
| 9 | +import java.util.LinkedList; |
12 | 10 |
|
13 | 11 | public class NewBingGoGoServerWebSocket extends NanoWSD.WebSocket { |
14 | 12 | NewBingGoGoClientWebSocket newBingGoGoClientWebSocket; |
15 | | - ScheduledFuture<?> task; |
16 | | - public NewBingGoGoServerWebSocket(NanoHTTPD.IHTTPSession handshakeRequest, ScheduledExecutorService executor) { |
| 13 | + LinkedList<String> messList = new LinkedList<>(); |
| 14 | + public NewBingGoGoServerWebSocket(NanoHTTPD.IHTTPSession handshakeRequest) { |
17 | 15 | super(handshakeRequest); |
18 | | - task = executor.scheduleAtFixedRate(() -> { |
19 | | - try { |
20 | | - ping(new byte[1]); |
21 | | - } catch (IOException e) { |
22 | | - task.cancel(false); |
23 | | - } |
24 | | - }, 2, 2, TimeUnit.SECONDS); |
25 | | - |
26 | 16 | URI url; |
27 | 17 | try { |
28 | 18 | url = new URI("wss://sydney.bing.com/sydney/ChatHub"); |
29 | 19 | } catch (URISyntaxException e) { |
30 | 20 | throw new RuntimeException(e);//这个异常这辈子都不会出的 |
31 | 21 | } |
32 | 22 |
|
33 | | - newBingGoGoClientWebSocket = new NewBingGoGoClientWebSocket(url,this); |
34 | | - newBingGoGoClientWebSocket.connect(); |
| 23 | + newBingGoGoClientWebSocket = new NewBingGoGoClientWebSocket(url,this,messList); |
35 | 24 | } |
36 | 25 |
|
37 | 26 | @Override |
38 | 27 | protected void onOpen() { |
39 | | - |
| 28 | + newBingGoGoClientWebSocket.connect(); |
40 | 29 | } |
41 | 30 |
|
42 | 31 | @Override |
43 | 32 | protected void onClose(NanoWSD.WebSocketFrame.CloseCode code, String reason, boolean initiatedByRemote) { |
44 | | - task.cancel(false); |
45 | 33 | newBingGoGoClientWebSocket.close(); |
46 | 34 | } |
47 | 35 |
|
48 | 36 | @Override |
49 | 37 | protected void onMessage(NanoWSD.WebSocketFrame message) { |
50 | | - newBingGoGoClientWebSocket.send(message.getTextPayload()); |
| 38 | + if(newBingGoGoClientWebSocket.isOpen()){ |
| 39 | + newBingGoGoClientWebSocket.send(message.getTextPayload()); |
| 40 | + }else { |
| 41 | + messList.addLast(message.getTextPayload()); |
| 42 | + } |
51 | 43 | } |
52 | 44 |
|
53 | 45 | @Override |
54 | 46 | protected void onPong(NanoWSD.WebSocketFrame pong) { |
55 | | - |
| 47 | + newBingGoGoClientWebSocket.sendPing(); |
56 | 48 | } |
57 | 49 |
|
58 | 50 | @Override |
59 | 51 | protected void onException(IOException exception) { |
60 | | - task.cancel(false); |
61 | 52 | newBingGoGoClientWebSocket.close(); |
62 | 53 | } |
63 | 54 | } |
0 commit comments