socket

客户端

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("{\n" +
            "  \"id\": 100,\n" +
            "  \"name\": \"\",\n" +
            "  \"type\": 1,\n" +
            "  \"content\": {\n" +
            "    \"cpu\": 50,\n" +
            "    \"mem\": 20\n" +
            "  }\n" +
            "}");

    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();
}

 

posted @ 2021-02-22 15:13  An-Optimistic-Person  阅读(46)  评论(0编辑  收藏  举报