安卓websocket

private WebSocketClient webSocketInit(String ip, int port) {
    // 将需要连接的 server 端的 IP 地址和端口
    String ws = "ws://" + ip + ":" + port;
    // 初始化 client,并重写其中相关函数
    try {
        client = new WebSocketClient(new URI(ws), new Draft_6455()) {
            //client连接成功
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
   
       
            }

            //接收消息逻辑处理
            @Override
            public void onMessage(String msgs) {
                // msg 的最外层套了一层 双引号
                try{
                    Long rectime = getNowTime();
                    Long ti = rectime - startfacetoserver;
                    Message msg = new Message();
                    msg.what = 1;
                    Bundle bundle = new Bundle();
                    bundle.putString("msgs", msgs);
                    bundle.putLong("webtime", ti);
                    msg.setData(bundle);
                    handlers.sendMessage(msg);
                }catch (Exception e){
                    System.out.println(e);
                }
            }

            //关闭连接断开连接
            @Override
            public void onClose(int i, String s, boolean b) {
                globalVariablex.setConnectflag(false);
                connectFlag = false;
                webSocketConnectStatus = true;
            }

            //发生错误关闭连接
            @Override
            public void onError(Exception e) {
                connectFlag = false;
                globalVariablex.setConnectflag(false);
                webSocketConnectStatus = true;
                e.printStackTrace();
            }
        };
    } catch (Exception e) {
        connectFlag = false;
        globalVariablex.setConnectflag(false);
        webSocketConnectStatus = true;
    }
    return client;
}
//webSocket client 连接
public void clientConnect(String ip, int port) {
    try {
        webSocketConnectStatus = false;
        client = webSocketInit(ip, port);
        client.connect();
    } catch (Exception e) {
        webSocketConnectStatus = true;
    }
}

发送数据用client.send(String data)

//接收数据在onmessage触发

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值