【安卓-tio】安卓集成t-io

创建一个新的安卓项目,在这不做详细讲解

假设已经创建了一个安卓项目

在maven仓库找到tio的依赖方式

选择gradle,加到安卓应用的依赖里

build.gradle

 点击sync now ,进行下载

切换到project 视图

会看到已经下载下来了,

那么怎么用呢,下面我们创建一个tcp 客户端,模拟连接服务端的例子

使用tio ,需要创建自己的

handler,listener ,packet 

如下,我创建了tcp 客户端的 handler,listener,packet 

代码如下:

XsTestHandler继承   ClientAioHandler
package com.xsiot.trashcan.tio;

import android.util.Log;

import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.TioConfig;
import org.tio.core.exception.TioDecodeException;
import org.tio.core.intf.Packet;

import java.nio.ByteBuffer;

public class XsTestHandler implements ClientAioHandler {


    @Override
    public Packet heartbeatPacket(ChannelContext channelContext) {
        return null;
    }

    @Override
    public Packet decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws TioDecodeException {

        Log.i("接收到信息:","信息长度:"+readableLength);

        return null;
    }

    @Override
    public ByteBuffer encode(Packet packet, TioConfig tioConfig, ChannelContext channelContext) {

        Log.i("发送前编码","信息:");
        XsTestPacket packet1 = (XsTestPacket)packet;

        ByteBuffer buffer = ByteBuffer.allocate(packet1.getMsg().getBytes().length);
        buffer.put(packet1.getMsg().getBytes());
        return buffer;
    }

    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {

    }
}
XsTestListener 实现ClientAioListener接口
package com.xsiot.trashcan.tio;

import android.util.Log;

import org.tio.client.intf.ClientAioListener;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;

public class XsTestListener implements ClientAioListener {
    @Override
    public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception {
        Log.i("连接成功了!","哈哈");


        XsTestPacket packet = new XsTestPacket();
        packet.setMsg("你好" );


        Tio.bSend(channelContext,packet);
    }

    @Override
    public void onAfterDecoded(ChannelContext channelContext, Packet packet, int packetSize) throws Exception {

    }

    @Override
    public void onAfterReceivedBytes(ChannelContext channelContext, int receivedBytes) throws Exception {
        Log.i("onAfterReceivedBytes接收到信息:","信息长度"+receivedBytes);
    }

    @Override
    public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) throws Exception {
        Log.i("发送成功了!","哈哈");
    }

    @Override
    public void onAfterHandled(ChannelContext channelContext, Packet packet, long cost) throws Exception {

    }

    @Override
    public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception {

    }
}
XsTestPacket  继承 Packet
package com.xsiot.trashcan.tio;

import org.tio.core.intf.Packet;

public class XsTestPacket  extends Packet {

  String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

启动类

package com.xsiot.trashcan.tio;

import android.util.Log;

import org.tio.client.ClientChannelContext;
import org.tio.client.ClientTioConfig;
import org.tio.client.ReconnConf;
import org.tio.client.TioClient;
import org.tio.client.intf.ClientAioHandler;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.Node;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;

import java.io.IOException;
import java.util.logging.Handler;

public class XsTestTioStart {




    public  static  void  startClient(){
        ClientAioHandler handler = new XsTestHandler();

        ClientAioListener listener = new XsTestListener();
        ClientTioConfig config;
        // 用来自动连接的,不想自动连接请设为null
        ReconnConf reconnConf = new ReconnConf(5000L);
        config = new ClientTioConfig(handler,listener,reconnConf);

        try {
            TioClient client = new TioClient(config);
            String serverIp = "192.168.0.100";
            int port = 10001;
            Node serverNode = new Node(serverIp,port);
            ClientChannelContext channelContext = client.connect(serverNode,5000  );

            Log.i("连接成功:","客户端端口:"+channelContext.getClientNode().getPort());




        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}

在默认的activity里调用

package com.xsiot.trashcan;

import androidx.appcompat.app.AppCompatActivity;

import android.app.StatusBarManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.xsiot.trashcan.tio.XsTestTioStart;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        XsTestTioStart.startClient();

        setContentView(R.layout.activity_main);



    }

    private void startTcpClient() {




    }


}

启动APP,但是启动失败,发现缺少网络访问权限。

没有联网权限,

/System.err: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
W/System.err: SLF4J: Defaulting to no-operation (NOP) logger implementation
    SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
W/System.err: java.net.SocketException: Permission denied
W/System.err:     at sun.nio.ch.Net.socket0(Native Method)
        at sun.nio.ch.Net.socket(Net.java:420)
        at sun.nio.ch.Net.socket(Net.java:413)
        at sun.nio.ch.AsynchronousSocketChannelImpl.<init>(AsynchronousSocketChannelImpl.java:90)
        at sun.nio.ch.UnixAsynchronousSocketChannelImpl.<init>(UnixAsynchronousSocketChannelImpl.java:102)
        at sun.nio.ch.LinuxAsynchronousChannelProvider.openAsynchronousSocketChannel(LinuxAsynchronousChannelProvider.java:88)
        at java.nio.channels.AsynchronousSocketChannel.open(AsynchronousSocketChannel.java:169)
        at org.tio.client.TioClient.connect(TioClient.java:353)
        at org.tio.client.TioClient.connect(TioClient.java:329)
        at org.tio.client.TioClient.connect(TioClient.java:420)
        at org.tio.client.TioClient.connect(TioClient.java:314)
        at com.xsiot.trashcan.tio.XsTestTioStart.startClient(XsTestTioStart.java:34)
        at com.xsiot.trashcan.MainActivity.onCreate(MainActivity.java:45)
W/System.err:     at android.app.Activity.performCreate(Activity.java:7171)
        at android.app.Activity.performCreate(Activity.java:7162)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2931)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3086)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1816)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6718)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

如何增加联网权限呢:

在AdroidManifest.xml文件里增加权限

 代码:

    <!--增加联网权限-->
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

用网络调试工具,模拟启动一个服务端,

 启动程序:

 

 到这,就能够实现安卓tcp 客户端连接服务端,并且进行消息推送了

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值