客户端
public static void main(String[] args) throws URISyntaxException, InterruptedException { WebSocketClient socketClient = new WebSocketClient(new URI("ws://127.0.0.1:1555")) { @Override public void onOpen(ServerHandshake serverHandshake) { System.out.println("onOpen"); } @Override public void onMessage(String s) { System.out.println(s); } @Override public void onClose(int i, String s, boolean b) { System.out.println("onClose"); } @Override public void onError(Exception e) { System.out.println("onError"); } }; socketClient.connectBlocking(10000, TimeUnit.SECONDS); /*while (!socketClient.getReadyState().equals(ReadyState.OPEN)) { System.out.println("连接中···请稍后"); }*/ socketClient.send("{ " + " "id": 100, " + " "name": "", " + " "type": 1, " + " "content": { " + " "cpu": 50, " + " "mem": 20 " + " } " + "}"); System.out.println(""); }
服务器
public static void main(String[] args) { DoubleMap<WebSocket, String> a = new DoubleMap<>(); WebSocketServer webSocketServer = new WebSocketServer(new InetSocketAddress(1555)) { public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) { System.out.println("onOpen"); a.put(webSocket, ""); } public void onClose(WebSocket webSocket, int i, String s, boolean b) { System.out.println("onClose"); a.removeByKey(webSocket); } public void onMessage(WebSocket webSocket, String s) { webSocket.send("{hvajsdhbgasjhda}"); System.out.println(s); } public void onError(WebSocket webSocket, Exception e) { System.out.println("onError"); } public void onStart() { System.out.println("onStart"); } }; webSocketServer.start(); }