最近看GitHub发现有一个不错的第三方库oksocket,封装的很好,自带连接响应和心跳包等,确实很不错
地址:https://github.com/xuuhaoo/OkSocket 大家有兴趣可以去看看,话不多说,直接上代码,一些基础的设置大家可以按官方的来,配置完后就开始开心撸代码了
1、首先声明一个activity和service,activity负责一些连接的控制(也就是按钮)加数据读写等。
service负责与服务器的连接,和数据处理,activity用aidl进行通讯
activity代码
class MainActivity : AppCompatActivity(),View.OnClickListener{
//由AIDL文件生成的Java类
private var data: SocketAidlInterface? = null
private var TAG="MainActivity"
//标志当前与服务端连接状况的布尔值,false为未连接,true为连接中
private var mBound=false
override fun onClick(v: View?) {
if (!mBound) {
attemptToBindService()
Toast.makeText(this, "当前与服务端处于未连接状态,正在尝试重连,请稍后再试", Toast.LENGTH_SHORT).show()
return
}
if(data==null)
return
when(v!!.id){
R.id.connection->{
//服务器连接
data!!.socketConnetion("192.168.227.1",1000)
}
//发送数据
R.id.send->{
data!!.writeData("hello")
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
openServer.setOnClickListener(this)
connection.setOnClickListener(this)
send.setOnClickListener(this)
}
//连接服务器
private fun attemptToBindService() {
val intent = Intent()
Log.e(TAG, " connected now")
intent.action = "com.andrem.gute.socketaidlinterface" //在AndroidManifest.xml进行配置隐形启动action
intent.`package`= "com.andrem.gute.tourhotel" //你的包名
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)
}
private val mServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
Log.e(TAG, "service connected")
data = SocketAidlInterface.Stub.asInterface(service)
mBound = true
if (data != null) {
try {
val s= data!!.socketConnetion("192.168.227.1",1000)
Log.e(TAG,s)
} catch (e: RemoteException) {
e.printStackTrace()
}
}
}
override fun onServiceDisconnected(name: ComponentName) {
Log.e(TAG, "service disconnected")
mBound = false
}
}
override fun onStart() {
super.onStart()
attemptToBindService()
}
override fun onStop() {
super.onStop()
unbindService(mServiceConnection)
}
}
service代码,写的很简单主要看ConnectionDataAidl类
class SocketConnectionService : Service() {
override fun onBind(intent: Intent): IBinder? {
return ConnectionDataAidl()
}
}
ConnectionDataAidl.kt代码,设置适配器负责连接响应和数据读写,通过aidl与activity进行数据交互
class ConnectionDataAidl : SocketAidlInterface.Stub() {
private var mInfo: ConnectionInfo? = null
private var mOkOptions: OkSocketOptions? = null
private var mManager: IConnectionManager? = null
private var serverData="null"
override fun socketConnetion(ip: String?, port: Int): String {
initManager(ip,port)
return if (!mManager!!.isConnect) {
mManager!!.connect()
"Connecting"
} else {
mManager!!.disconnect()
"DisConnecting"
}
}
private fun initManager(ip: String?, port: Int){
mInfo = ConnectionInfo(ip, port)
mOkOptions = OkSocketOptions.Builder()
.setReconnectionManager(NoneReconnect())
.setWritePackageBytes(1024)
.setCallbackInThread(false)
.build()
mManager = OkSocket.open(mInfo).option(mOkOptions)
mManager!!.registerReceiver(adapter)
}
override fun disconnecting() {
if (mManager == null) {
return
}
mManager!!.disconnect()
}
override fun writeData(data: String?) {
if (mManager == null) {
return
}
if (!mManager!!.isConnect) {
return
} else {
if (TextUtils.isEmpty(data!!.trim())) {
return
}
val msgDataBean=MsgDataBean(data)
// MsgDataBean msgDataBean = new MsgDataBean(msg);
mManager!!.send(msgDataBean)
}
}
override fun readResponse(): String {
return serverData
}
private val adapter = object : SocketActionAdapter() {
override fun onSocketConnectionSuccess(context: Context?, info: ConnectionInfo?, action: String?) {
mManager!!.send(HandShake())
}
override fun onSocketDisconnection(context: Context?, info: ConnectionInfo?, action: String?, e: Exception?) {
if (e != null) {
logSend("异常断开:" + e.message)
} else {
logSend("正常断开")
}
}
override fun onSocketConnectionFailed(context: Context?, info: ConnectionInfo?, action: String?, e: Exception?) {
logSend("连接失败")
}
override fun onSocketReadResponse(context: Context?, info: ConnectionInfo?, action: String?, data: OriginalData?) {
super.onSocketReadResponse(context, info, action, data)
val str = String(data!!.bodyBytes, Charset.forName("utf-8"))
}
override fun onSocketWriteResponse(context: Context?, info: ConnectionInfo?, action: String?, data: ISendable?) {
super.onSocketWriteResponse(context, info, action, data)
serverData = String(data!!.parse(), Charset.forName("utf-8"))
logSend(serverData)
}
override fun onPulseSend(context: Context?, info: ConnectionInfo?, data: IPulseSendable?) {
super.onPulseSend(context, info, data)
serverData = String(data!!.parse(), Charset.forName("utf-8"))
logSend(serverData)
}
}
private fun logSend(s: String) {
Log.e("TAG",s)
}
}
最后是SocketAidlInterface代码
interface SocketAidlInterface {
//写数据
void writeData(String data);
//获取放回数据
String readResponse();
//socket连接
String socketConnetion(String ip,int port);
//断开socket连接
void disconnecting();
}
主要代码就是这样,不足的请指出。
源码地址:https://download.csdn.net/download/qq_36480491/10767472