Giter Site home page Giter Site logo

oksocket's Introduction

OkSocket Document

An blocking socket client for Android applications.

License Download

Read this in other languages: 简体中文

OkSocket Introduce

Android Oksocket Library is socket client solution base on java blocking socket.You can use it to develop line chat rooms or data transmission etc.

Maven Configuration

Automatic Import(Recommend)
  • OkSocket Library is uploaded in JCenter,please add the code into your project gradle file
allprojects {
    repositories {
        jcenter()
    }
}
  • Make sure you already done with put JCenter into repositories blocking in project gradle files than you need put this into Module build.gradle file
dependencies {
        compile 'com.tonystark.android:socket:1.0.0'
}

Manifest Configuration

  • Put the Permissions into AndroidManifest.xml file:
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.READ_PROFILE"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Proguard Configuration

  • Put this code into your Proguard file:
-dontwarn com.xuhao.android.libsocket.**
-keep class com.xuhao.android.socket.impl.abilities.** { *; }
-keep class com.xuhao.android.socket.impl.exceptions.** { *; }
-keep class com.xuhao.android.socket.impl.EnvironmentalManager { *; }
-keep class com.xuhao.android.socket.impl.BlockConnectionManager { *; }
-keep class com.xuhao.android.socket.impl.UnBlockConnectionManager { *; }
-keep class com.xuhao.android.socket.impl.SocketActionHandler { *; }
-keep class com.xuhao.android.socket.impl.PulseManager { *; }
-keep class com.xuhao.android.socket.impl.ManagerHolder { *; }
-keep class com.xuhao.android.socket.interfaces.** { *; }
-keep class com.xuhao.android.socket.sdk.** { *; }
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}
-keep class com.xuhao.android.socket.sdk.OkSocketOptions$* {
    *;
}

OkSocket Initialization

  • To copy the following code into the project Application class onCreate (), OkSocket will automatically detect the environment and complete the configuration
public class MyApplication extends Application {
	@Override
	public void onCreate() {
		super.onCreate();
		//The main process needs to be distinguished at the beginning of the primary process.
		OkSocket.initialize(this);
		//If you need to open the Socket debug log, configure the following
		//OkSocket.initialize(this,true);
	}
}

Call The Demonstration

Simple connections
  • OkSocket will default to each Open new channels for cache management, only in the first call to the Open method is created when the ConnectionManager manager, after the caller can pass retrieves a reference to the ConnectionManager, continue to call the related method
  • ConnectionManager is mainly responsible for the Socket connection, disconnect, send message, heartbeat management, etc.
//Connection parameter Settings (IP, port number), which is also a unique identifier for a connection, with different connections, at least one of the two values in this parameter
ConnectionInfo info = new ConnectionInfo("127.0.0.1", 8088);
//Call OkSocket, open the channel for this connection, and call the channel's connection method for physical connections.
OkSocket.open(info).connect();
A connection with callback
  • Registered Socket channel listener, each Socket channel listener in isolation from each other, so if in a project to connect multiple Socket channel, need to be registered in each Socket channel listeners own connections, connection listener OkSocket library is the the only way to interact with the caller
//After obtaining the connection manager from the above method...
manager.registerReceiver(new SocketActionAdapter(){
	@Override
	public void onSocketConnectionSuccess(Context context, ConnectionInfo info, String action) {
	 Toast.makeText(context, "The connection is successful", LENGTH_SHORT).show();
	}
});
//call the channel's connection method for physical connections.
manager.connect();
Configurable connections
  • Obtain OkSocketOptions behavior belongs to the more advanced behavior, each Socket connection will correspond to a OkSocketOptions, if call Open for the first time is not specified OkSocketOptions, OkSocket library will use a default configuration object, the default configuration, please see the class documentation
ConnectionInfo info = new ConnectionInfo("127.0.0.1", 8088);
IConnectionManager manager = OkSocket.open(info);
//Gets the reference object for the current connection channel
OkSocketOptions options= manager.getOption();
//Build a builder class based on the current reference object
OkSocketOptions.Builder builder = new OkSocketOptions.Builder(options);
//Modify the parameter Settings (refer to the class documentation for other references)
builder.setSinglePackageBytes(size);
//Create a new reference object and set it to the channel
manager.option(builder.build());
manager.connect();
How do I send data
//Class A:
//...Define the data structure to be sent...
public class TestSendData implements ISendable {
	private String str = "";

    public TestSendData() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("cmd", 14);
            jsonObject.put("data", "{x:2,y:1}");
            str = jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public byte[] parse() {
    	//Build the byte array according to the server's parsing rules
        byte[] body = str.getBytes(Charset.defaultCharset());
        ByteBuffer bb = ByteBuffer.allocate(4 + body.length);
        bb.order(ByteOrder.BIG_ENDIAN);
        bb.putInt(body.length);
        bb.put(body);
        return bb.array();
    }
}

//Class B:
private IConnectionManager mManager;
//...Omit the connection and set the associated code for the callback...
@Override
public void onSocketConnectionSuccess(Context context, ConnectionInfo info, String action) {
     //Chain programming call
     OkSocket.open(info)
     	.send(new TestSendData());
     ============OR==============
     //The IConnectManager can also be saved as a member variable.
     mManager = OkSocket.open(info);
     if(mManager != null){
        mManager.send(new TestSendData());
     }
}
How to receive data
  • The OkSocket client receives server data in a certain format, and the client's OkSocketOptions provides the interface to modify the default header parsing rules. See below for the default package body parsing rules img
  • As above, the contents of the header for 4 bytes of type int, the int value identifies the inclusions the length of the data area(body area), this is the default resolution, if you need custom header please according to the following method.
//Set the custom parsing header
OkSocketOptions.Builder okOptionsBuilder = new OkSocketOptions.Builder(mOkOptions);
okOptionsBuilder.setHeaderProtocol(new IHeaderProtocol() {
    @Override
    public int getHeaderLength() {
    	//Returns a custom header length that automatically parses the length of the head
        return 0;
    }

    @Override
    public int getBodyLength(byte[] header, ByteOrder byteOrder) {
    	//The length of the body is parsed from the header, byteOrder is the sequence of bytes that you configured in the parameter, which can be easily parsed using ByteBuffer
        return 0;
    }
});
//Set the modified parameter to the connection manager
mManager.option(okOptionsBuilder.build());


//...After the parsing header is properly set...
@Override
public void onSocketReadResponse(Context context, ConnectionInfo info, String action, OriginalData data) {
    //Follow the above rules, this callback can be normal received the data returned from the server, the data in the OriginalData, for byte [] array, the array data already processed byte sequence problem, can be used in the ByteBuffer directly
}
How to keep a heartbeat
//Class A:
//...Define the heartbeat data type required by the heartbeat manager...
public class PulseData implements IPulseSendable {
	private String str = "pulse";

    @Override
    public byte[] parse() {
    //Build the byte array according to the server's parsing rules
        byte[] body = str.getBytes(Charset.defaultCharset());
        ByteBuffer bb = ByteBuffer.allocate(4 + body.length);
        bb.order(ByteOrder.BIG_ENDIAN);
        bb.putInt(body.length);
        bb.put(body);
        return bb.array();
    }
}

//Class B:
private IConnectionManager mManager;
private PulseData mPulseData = new PulseData;
@Override
public void onSocketConnectionSuccess(Context context, ConnectionInfo info, String action) {
     //Chain programming call. Set heartbeat data for the heartbeat manager. A connection only has a heartbeat manager, so the data is set only once. If disconnected, please set it again.
     OkSocket.open(info)
     	.getPulseManager()
     	.setPulseSendable(mPulseData)
     	.pulse();//Start the heartbeat. 
     	//After the heartbeat, the heartbeat manager will automatically carry out the heartbeat trigger
  		======OR======
     mManager = OkSocket.open(info);
     if(mManager != null){
        PulseManager pulseManager = mManager.getPulseManager();
        //Set the heartbeat data to the heartbeat manager, and a connection has only one heartbeat manager, so the data is only set once, and if disconnected, set it again.
        pulseManager.setPulseSendable(mPulseData);
        //Start the heartbeat. After the heartbeat, the heartbeat manager will automatically carry out the heartbeat trigger
        pulseManager.pulse();
     }
}
The heartbeat feed dog
  • Feed the dog because our client needs to know the Socket server received the heart data, so the server after I receive my heartbeat data need to reply the client after receiving the response data, we need to be local dog operations, or when more than a certain number of times the heart data, but did not get feed the dog, the dog will connect the disconnect reconnection.
private IConnectionManager mManager;
//When the client receives the message
@Override
public void onSocketReadResponse(Context context, ConnectionInfo info, String action, OriginalData data) {
	if(mManager != null && It's the heartbeat return package){
		//Whether it is a heartbeat return package, you need to resolve the data returned by the server to know
		//Feed dog
	    mManager.getPulseManager().feed();
	}
}
Manual trigger heartbeat
private IConnectionManager mManager;
//...in anywhere...
mManager = OkSocket.open(info);
if(mManager != null){
	PulseManager pulseManager = mManager.getPulseManager();
	//Manually trigger a heartbeat (mainly used for situations requiring manual control of trigger timing)
	pulseManager.trigger();
}

Explanation Of OkSocketOptions And Callbacks

  • OkSocketOptions

    • Socket communication modemIOThreadMode
    • Connection is managed saveisConnectionHolden
    • Write byte ordermWriteOrder
    • Read byte ordermReadByteOrder
    • Header protocolmHeaderProtocol
    • The total length of a single packet is sentmSendSinglePackageBytes
    • Cache byte length for single readsmReadSingleTimeBufferBytes
    • Pulse frequency intervalmPulseFrequency
    • Maximum number of pulse loss (loss of feed dog)mPulseFeedLoseTimes
    • Backstage survival time (minutes)mBackgroundLiveMinute
    • Connection timeout (seconds)mConnectTimeoutSecond
    • Maximum number of megabytes (MB) reading datamMaxReadDataMB
    • Reconnection managermReconnectionManager
  • ISocketActionListener

    • A callback for the Socket reader/writer thread startonSocketIOThreadStart
    • A callback for the Socket read/write thread shutdownonSocketIOThreadShutdown
    • Socket connection status changesonSocketDisconnection
    • Socket connection successful callbackonSocketConnectionSuccess
    • Socket connection failed callbackonSocketConnectionFailed
    • The Socket reads the callback from the server to the byteonSocketReadResponse
    • Socket write to server byte back callbackonSocketWriteResponse
    • Send a heartbeat backonPulseSend
   Copyright [2017] [徐昊]

   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.

oksocket's People

Contributors

xuuhaoo avatar

Watchers

 avatar  avatar  avatar

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.