zoukankan      html  css  js  c++  java
  • 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("{
    " +
                "  "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();
    }
  • 相关阅读:
    cookie处理函数练习(为我所写,非我所想:改善面向对象)
    TypeScript的4种编译方式
    如何调用外部的Web API
    Json to JObject转换的使用方法
    Json.NET读取和写入Json文件
    XTemplate语法基础
    node.js xtemplate的使用实例
    node.js express安装及示例网站搭建
    各大互联网公司前端面试题(HTML/CSS)
    各大互联网公司前端面试题
  • 原文地址:https://www.cnblogs.com/gjq1126-web/p/14430473.html
Copyright © 2011-2022 走看看