android 简单websocketclient

工具类 

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.wolong.rtmp.Constants;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

public class WebClient extends WebSocketClient {

    private static WebClient mWebClient;
    private static String mWebMsg;


    /**
     *  路径为ws+服务器地址+服务器端设置的子路径+参数(这里对应服务器端机器编号为参数)
     *  如果服务器端为https的,则前缀的ws则变为wss
     */
    private static final String mAddress = "ws://192.168.2.11:8080/socketServer/websocket";

    public WebClient(URI uri) {
        super(uri);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
    }

    @Override
    public void onMessage(String s) {
        mWebMsg = s;
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        if(mWebClient != null){
            mWebClient.close();
        }
    }

    @Override
    public void onError(Exception e) {
        e.printStackTrace();
    }

    public static WebClient getInstance() {
        if (mWebClient == null) {
            synchronized (WebClient.class) {
                if (mWebClient == null) {
                    try {
                        mWebClient = new WebClient(new URI(mAddress));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
        return mWebClient;
    }

    /**
     * 初始化
     */
    public static void initWebSocket(final String username){
        new Thread(new Runnable() {
           @Override
            public void run() {
               Looper.prepare();
                try {
                    mUserName = username;
                    mWebClient = new WebClient(new URI(mAddress));
                    boolean flag = mWebClient.connectBlocking();
                    Log.d("msg","连接:"+flag);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Looper.loop();
            }
        }).start();
    }

 MainActivity.java

WebClient.initWebSocket();//启动

WebClient.getInstance().send();//send消息

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值