Giter Site home page Giter Site logo

shenhuanet / sensocketclient Goto Github PK

View Code? Open in Web Editor NEW
6.0 3.0 1.0 199 KB

Sen Socket Client Core for Android develop.Supports TCP/UDP application development based on Java NIO/BIO technology.

License: Apache License 2.0

Kotlin 13.87% Java 86.13%
socket-client tcp-client udp-client android-library

sensocketclient's Introduction

SenSocketClient

jCenter jCenter jCenter Build Status Hex.pm

Sen Socket Client Core for Android develop.Supports TCP/UDP application development based on Java NIO/BIO technology.

logo

Usage

Example for only use TCP client,you can change 'sensocket-tcp' to 'sensocket-udp' if only use UDP client.Of course, you can use it together

Maven build settings

build.gradle

dependencies {
  compile 'com.shenhua.libs:sensocket-tcp:1.0.0'
}

or maven

<dependency>
  <groupId>com.shenhua.libs</groupId>
  <artifactId>sensocket-tcp</artifactId>
  <version>1.0.0</version>
  <type>pom</type>
</dependency>

or lvy

<dependency org='com.shenhua.libs' name='sensocket-tcp' rev='1.0.0'>
  <artifact name='sensocket-tcp' ext='pom' ></artifact>
</dependency>

Code

Kotlin (TCP-NIO)

private var tcpNioClient: TcpNioClient? = null
private var executor: ExecutorService = Executors.newSingleThreadExecutor()

fun connect() {
    executor!!.execute {
        val socketAddress = InetSocketAddress(ip, port)
        if (tcpNioClient == null) {
            tcpNioClient = TcpNioClient(mMessageProcessor, mConnectResultListener)
            tcpNioClient!!.setConnectAddress(arrayOf(TcpAddress(socketAddress.hostName, socketAddress.port)))
        }
        tcpNioClient!!.connect()
    }
}

fun send() {
    executor!!.execute {
        mMessageProcessor.send(tcpNioClient!!, "hello world".toByteArray())
    }
}

override fun disConnect() {
    tcpNioClient?.disconnect()
}

private val mMessageProcessor = object : BaseMessageProcessor() {
    override fun onReceiveMessages(mClient: BaseClient, mQueen: LinkedList<Message>) {
        for (i in mQueen.indices) {
            val message = mQueen[i]
            val s = String(message.data, message.offset, message.length)
            println(s)
            activity.runOnUiThread {
                tvMessage.append("\n$s")
            }
        }
    }
}

private val mConnectResultListener = object : IConnectListener {
    override fun onConnectionSuccess() {
        println("onConnectionSuccess")
    }
    override fun onConnectionFailed() {
        println("onConnectionFailed")
    }
}

override fun onDestroyView() {
    tcpNioClient?.disconnect()
    super.onDestroyView()
}

Java (TCP-NIO)

private TcpNioClient tcpNioClient;
private ExecutorService executor = Executors.newSingleThreadExecutor();

public void connect() {
    executor.execute(new Runnable() {
        @Override
        public void run() {
            TcpAddress tcpAddress = new TcpAddress(host, port);
            if (tcpNioClient == null) {
                tcpNioClient = new TcpNioClient(mMessageProcessor, mConnectResultListener);
                tcpNioClient.setConnectAddress(new TcpAddress[]{tcpAddress});
            }
            tcpNioClient.connect();
        }
    });
}

public void send() {
    executor.execute(new Runnable() {
        @Override
        public void run() {
            mMessageProcessor.send(tcpNioClient, "hello world".getBytes());
        }
    });
}

public void disConnect() {
    tcpNioClient.disconnect();
}

private BaseMessageProcessor mMessageProcessor = new BaseMessageProcessor() {
    @Override
    public void onReceiveMessages(BaseClient mClient, LinkedList<Message> mQueen) {
        for (int i = 0; i < mQueen.size(); i++) {
            Message message = mQueen.get(i);
            String msg = new String(message.data, message.offset, message.length);
            System.out.println(msg);
        }
    }
};

private IConnectListener mConnectResultListener = new IConnectListener() {
    @Override
    public void onConnectionSuccess() {
        System.out.println("onConnectionSuccess");
    }
    @Override
    public void onConnectionFailed() {
        System.out.println("onConnectionFailed");
    }
};

Sample Screenshot

About Me

CSDN:http://blog.csdn.net/klxh2009
JianShu:http://www.jianshu.com/u/12a81897d5bc

License

Copyright 2018 shenhuanet

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.