SocketHandler.java
1.43 KB
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
package com.huaheng.framework.config;
import org.apache.http.client.utils.URIBuilder;
import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
@ClientEndpoint
public class SocketHandler {
public static Session session;
public SocketHandler() {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
URIBuilder uriBuilder = new URIBuilder();
uriBuilder.setScheme("ws");
uriBuilder.setHost("127.0.0.1");
uriBuilder.setPort(8111);
URI uri = uriBuilder.build();
System.out.println(uri.toString());
session = container.connectToServer(this, new URI("ws://121.40.165.18:8800"));
} catch (DeploymentException | IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
@OnMessage
public void onMessage(String message) {
System.out.println(message);
// sendMessage("发送测试+"+System.currentTimeMillis());
}
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
System.out.println(session.getId());
}
public static void sendMessage(String str) {
try {
session.getBasicRemote().sendText(str);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}