我是靠谱客的博主 迷路野狼,最近开发中收集的这篇文章主要介绍Android Socket长连接框架OkSocket与C#做服务端进行通信的使用demo代码(),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

安卓客户端源码下载地址:https://download.csdn.net/download/Scorpio_gao/12645584

OkSocket简介

Android OkSocket是一款基于阻塞式传统Socket的一款Socket客户端整体解决方案.您可以使用它进行简单的基于Tcp协议的Socket通讯,当然,也可以进行大数据量复杂的Socket通讯,
支持单工,双工通讯.

 从github上下载了OkSocket源码引入项目中,如下所示:

Maven配置

  • OkSocket 目前仅支持 JCenter 仓库

在项目app目录下打开项目设置页面添加依赖如下所示:

 

 

 

混淆配置

  • 请避免混淆OkSocket,在Proguard混淆文件中增加以下配置:
  •  

 在Module的build.gradle文件中添加依赖配置

public class DefaultSendBean implements ISendable {
    protected String content = "";
//    @Override
//    public final byte[] parse() {
//        byte[] body = content.getBytes(Charset.defaultCharset());//Charset.forName("utf-8")   Charset.defaultCharset()
//        ByteBuffer bb = ByteBuffer.allocate(4 + body.length);
//        bb.order(ByteOrder.BIG_ENDIAN);
//        bb.putInt(body.length);
//        bb.put(body);
//        return bb.array();
//    }
        @Override
        public final byte[] parse() {
            byte[] body = content.getBytes(Charset.defaultCharset());
            return body;
        }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}
public class HandShakeBean extends DefaultSendBean {
    public HandShakeBean() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("cmd", 2);//握手
            jsonObject.put("handshake", "Hello Server");
            content = jsonObject.toString();
        } catch (JSONException e){
            e.printStackTrace();
        }
    }
}
public class PulseBean implements IPulseSendable {
    private String str = "";
    public PulseBean() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("cmd", 1);//心跳
            str = jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    @Override
    public byte[] parse() {
        byte[] body = str.getBytes(Charset.defaultCharset());
        return body;
    }
}

以下是主界面调用方法:

public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private EditText et1,et2;
    private TextView tv_1,tv_2;
    private ScrollView sv1,sv2;

    private ConnectionInfo mInfo;
    private IConnectionManager mManager;

    private SocketActionAdapter adapter = new SocketActionAdapter() {

        @Override
        public void onSocketConnectionSuccess(ConnectionInfo info, String action) {
            LogMyInfoSend("连接成功!");
//            mManager.send(new HandShakeBean());
//            mManager.getPulseManager().setPulseSendable(new PulseBean());

//            OkSocket.open(info).send(new TestSendData("1222222",0));//链式编程调用
            if (mManager != null) {
                mManager.send(new HandShakeBean());
            }
        }

        @Override
        public void onSocketDisconnection(ConnectionInfo info, String action, Exception e) {
            if (e != null) {
                LogMyInfoSend("异常断开(Disconnected with exception):" + e.getMessage());
            } else {
                LogMyInfoSend("正常断开(Disconnect Manually)");
            }
        }

        @Override
        public void onSocketConnectionFailed(ConnectionInfo info, String action, Exception e) {
            LogMyInfoSend("连接失败(Connecting Failed)");
        }

        @Override
        public void onSocketReadResponse(ConnectionInfo info, String action, OriginalData data) {
            String str = new String(data.getBodyBytes(), Charset.forName("utf-8"));
            //LogMyInfoReceive("收到数据:"+str);
            JsonObject jsonObject = new JsonParser().parse(str).getAsJsonObject();
            int cmd = jsonObject.get("cmd").getAsInt();
            if (cmd == 2) {//成功
                String handshake = jsonObject.get("handshake").getAsString();
                LogMyInfoReceive("握手成功! 收到:" + handshake + ". ");
                mManager.getPulseManager().setPulseSendable(new PulseBean());
            }else if (cmd == 1) {//心跳
                LogMyInfoReceive("收到心跳返回");
                mManager.getPulseManager().feed();
            } else if (cmd == 3) {//发送内容
                LogMyInfoReceive("收到返回:"+str);
//                Gson gson = new Gson();
//                TestSendData sendData = gson.fromJson(str, TestSendData.class);
//                if(sendData!=null){
//                    LogMyInfoReceive("收到返回:"+sendData.getContent()+"-"+sendData.getType());
//                }
            } else {
                LogMyInfoReceive("收到数据:"+str);
            }
        }

        @Override
        public void onSocketWriteResponse(ConnectionInfo info, String action, ISendable data) {
            byte[] bytes = data.parse();
            //bytes = Arrays.copyOfRange(bytes, 4, bytes.length);
            String str = new String(bytes, Charset.forName("utf-8"));
            JsonObject jsonObject = new JsonParser().parse(str).getAsJsonObject();
            int cmd = jsonObject.get("cmd").getAsInt();
            switch (cmd) {
                case 2: {
                    String handshake = jsonObject.get("handshake").getAsString();
                    LogMyInfoSend("发送握手数据:" + handshake);
                    mManager.getPulseManager().pulse();
                    break;
                }
                default:
                    LogMyInfoSend("发送:" + str);
            }
        }

        @Override
        public void onPulseSend(ConnectionInfo info, IPulseSendable data) {
            byte[] bytes = data.parse();
            //bytes = Arrays.copyOfRange(bytes, 4, bytes.length);
            String str = new String(bytes, Charset.forName("utf-8"));
            JsonObject jsonObject = new JsonParser().parse(str).getAsJsonObject();
            int cmd = jsonObject.get("cmd").getAsInt();
            if (cmd == 1) {
                LogMyInfoSend("发送心跳包(Heartbeat Sending)");
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext=this;
        et1=findViewById(R.id.et1);
        tv_1=findViewById(R.id.tv_1);
        tv_2=findViewById(R.id.tv_2);
        et2=findViewById(R.id.et2);
        sv1=findViewById(R.id.sv1);
        sv2=findViewById(R.id.sv2);
        initData();


    }

    private void initData() {
        mInfo = new ConnectionInfo("192.168.1.190", 8182);
//        mInfo = new ConnectionInfo("10.0.2.2", 5554);
        mManager = OkSocket.open(mInfo);
        final Handler handler = new Handler(Looper.getMainLooper());
        OkSocketOptions.Builder builder = new OkSocketOptions.Builder();
//        builder.setReconnectionManager(new NoneReconnect());//关闭重连管理器
        mManager.option(new OkSocketOptions.Builder(mManager.getOption()).setReconnectionManager(OkSocketOptions.getDefault()
                .getReconnectionManager()).build());//打开重连管理器
        long frequency = 5000;//心跳  脈搏頻率間隔毫秒數
        OkSocketOptions okOptions = new OkSocketOptions.Builder(mManager.getOption()).setPulseFrequency(frequency).build();
        mManager.option(okOptions);
        builder.setCallbackThreadModeToken(new OkSocketOptions.ThreadModeToken() {
            @Override
            public void handleCallbackEvent(ActionDispatcher.ActionRunnable runnable) {
                handler.post(runnable);
            }
        });

//        builder.setReaderProtocol(new IReaderProtocol(){
//            @Override
//            public int getHeaderLength() {
//                return 0;//您返回的值应符合服务器文档中的报文头的固定长度值(字节数)
//            }
//
//            @Override
//            public int getBodyLength(byte[] header, ByteOrder byteOrder) {
//                return header.length;
//            }
//        });

        mManager.option(builder.build());
        mManager.registerReceiver(adapter);

    }


    public void onClick(View v){
        switch (v.getId()){
            case R.id.bt1:
                LogMyInfoSend("打开连接");
                if (mManager == null) {
                    return;
                }
                if (!mManager.isConnect()) {
                    mManager.connect();
                }
                break;
            case R.id.bt2:
                LogMyInfoSend("关闭连接!");
                if (mManager == null) {
                    return;
                }
                mManager.disconnect();
                break;
            case R.id.bt3:
//                Toast.makeText(mContext, "bt3", Toast.LENGTH_SHORT).show();
//                if (mManager == null) { return;}
//                if (mManager.isConnect()) {
//                    mManager.getPulseManager().trigger();//手动触发一次心跳(主要用于一些需要手动控制触发时机的场景)
//                }
                String send_str=et2.getText().toString().trim();
                if(send_str==null ||send_str.length()<1){
                    Toast.makeText(mContext, "发送内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mManager != null&& mManager.isConnect()) {
                    mManager.send(new TestSendData(send_str,0));
                    LogMyInfoSend("推送数据:"+send_str);
                }else{
                    LogMyInfoSend("推送数据失败");
                }
                break;
            default:
                break;
        }
    }

    String content_send="";//发送记录
    public void LogMyInfoSend(String content){
        content_send+=content+"n";
        tv_1.setText(content_send);
        sv1.post(new Runnable() {
            @Override
            public void run() {
                sv1.fullScroll(ScrollView.FOCUS_DOWN);// 滚动到底部
                //sv1.fullScroll(ScrollView.FOCUS_UP);// 滚动到顶部部
            }
        });
    }
    String content_receive="";//接收记录
    public void LogMyInfoReceive(String content){
        content_receive+=content+"n";
        tv_2.setText(content_receive);
        sv2.post(new Runnable() {
            @Override
            public void run() {
                sv2.fullScroll(ScrollView.FOCUS_DOWN);// 滚动到底部
                //sv1.fullScroll(ScrollView.FOCUS_UP);// 滚动到顶部部
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mManager != null) {
            mManager.disconnect();
            mManager.unRegisterReceiver(adapter);
        }


    }
}

OkSocket参配选项及回调说明

  • OkSocketOptions

    • Socket通讯模式mIOThreadMode
    • 连接是否管理保存isConnectionHolden
    • 写入字节序mWriteOrder
    • 读取字节序mReadByteOrder
    • 头字节协议mHeaderProtocol
    • 发送单个数据包的总长度mSendSinglePackageBytes
    • 单次读取的缓存字节长度mReadSingleTimeBufferBytes
    • 脉搏频率间隔毫秒数mPulseFrequency
    • 脉搏最大丢失次数(狗的失喂次数)mPulseFeedLoseTimes
    • 后台存活时间(分钟)mBackgroundLiveMinute
    • 连接超时时间(秒)mConnectTimeoutSecond
    • 最大读取数据的兆数(MB)mMaxReadDataMB
    • 重新连接管理器mReconnectionManager
  • ISocketActionListener

    • Socket读写线程启动后回调onSocketIOThreadStart
    • Socket读写线程关闭后回调onSocketIOThreadShutdown
    • Socket连接状态由连接->断开回调onSocketDisconnection
    • Socket连接成功回调onSocketConnectionSuccess
    • Socket连接失败回调onSocketConnectionFailed
    • Socket从服务器读取到字节回调onSocketReadResponse
    • Socket写给服务器字节后回调onSocketWriteResponse
    • 发送心跳后的回调onPulseSend

 

 

 

 

最后

以上就是迷路野狼为你收集整理的Android Socket长连接框架OkSocket与C#做服务端进行通信的使用demo代码()的全部内容,希望文章能够帮你解决Android Socket长连接框架OkSocket与C#做服务端进行通信的使用demo代码()所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(37)

评论列表共有 0 条评论

立即
投稿
返回
顶部