目錄
效果展示
實(shí)現(xiàn)步驟
1.搭建服務(wù)端
這里我們用的是nodejs搭建的硫惕,由于我們用的不是最新標(biāo)準(zhǔn)的socket.io因此我們需要下載指定版本的socket.io
npm install socket.io@2.0.4
代碼如下:
'use strict'
var http = require('http');
var socketio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(3000, '0.0.0.0');
var io = socketio.listen(server);
io.on('connection', (sokcetClient) => {
console.log(sokcetClient.id);
sokcetClient.on('join', (roomId) => {
//加入房間
sokcetClient.join(roomId);
//通知某設(shè)備加入房間
sokcetClient.in(roomId).emit('joined', roomId, sokcetClient.id);
});
sokcetClient.on('leave', (roomId) => {
//離開(kāi)房間
sokcetClient.leave(roomId);
//通知某設(shè)備離開(kāi)房間
sokcetClient.in(roomId).emit('leaved', roomId, sokcetClient.id);
});
sokcetClient.on('sendRoomMsg',(roomId,msg)=>{
//向房間內(nèi)推送消息
sokcetClient.in(roomId).emit('receiveRoomMsg', msg);
})
});
其中socket.io中部分常用的函數(shù)及左右如下:
on:用于監(jiān)聽(tīng)對(duì)應(yīng)的事件夷家,接收的參數(shù)取決于emit發(fā)送的數(shù)據(jù)
emit:用于發(fā)送相應(yīng)的事件
in(roomId).emit:用于在相應(yīng)的房間內(nèi)發(fā)送事件
join(roomId):加入相應(yīng)的房間
leave(roomId):離開(kāi)相應(yīng)的房間
2.客戶端實(shí)現(xiàn)
1.引入依賴
https://socketio.github.io/socket.io-client-java/installation.html
這里由于服務(wù)器不是使用的最新的socketio熟尉,因此我們客戶端也引入1.0.0版本的庫(kù)
implementation ('io.socket:socket.io-client:1.0.0') {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
2.代碼實(shí)現(xiàn)
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
</data>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:padding="10dp"
tools:context=".MainActivity">
<Button
android:id="@+id/bt_connect"
android:text="連接"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/bt_joinroom"
android:text="加入房間"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/bt_disConnect"
android:text="斷開(kāi)連接"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/et_sendmsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/bt_sendmsg"
android:text="發(fā)送消息"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tv_chat"
android:layout_marginTop="10dp"
android:padding="10dp"
android:background="@drawable/shape_chat"
android:textColor="@color/black"
android:textSize="15sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
class MainActivity : AppCompatActivity() {
private lateinit var mainBinding: ActivityMainBinding
private var socket: Socket? = null
private var roomId = "111" //房間號(hào)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainBinding = DataBindingUtil.setContentView<ActivityMainBinding>(this,R.layout.activity_main)
mainBinding.lifecycleOwner = this
initListener()
}
private fun initListener() {
mainBinding.btConnect.setOnClickListener {
connectSocketIo()
}
mainBinding.btDisConnect.setOnClickListener {
socket?.let {
//發(fā)送離開(kāi)事件
it.emit("leave",roomId)
it.disconnect()
it.close()
}
}
mainBinding.btJoinroom.setOnClickListener {
socket?.let {
//發(fā)送加入事件
it.emit("join",roomId)
}
}
mainBinding.btSendmsg.setOnClickListener {
var msg = mainBinding.etSendmsg.text.toString()
//發(fā)送消息就是發(fā)送sendRoomMsg事件,然后服務(wù)器會(huì)進(jìn)行轉(zhuǎn)發(fā)
socket?.let {
it.emit("sendRoomMsg",roomId,msg)
addMsg2View(msg)
}
}
}
private fun connectSocketIo(){
socket = IO.socket("http://192.168.16.52:3000/").apply {
connect()
//接收joined事件莹菱,用于提醒有人加入房間了
on("joined") {
var roomId = it[0]
var clientId = it[1]
Log.e("加入","房間id:$roomId 客戶端id:$clientId")
runOnUiThread {
Toast.makeText(this@MainActivity,"客戶端:$clientId 加入房間",Toast.LENGTH_SHORT).show()
}
}
//接收receiveRoomMsg事件用于對(duì)房間消息的顯示
on("receiveRoomMsg") {
var roomMsg = it[0]
runOnUiThread {
addMsg2View(roomMsg as String)
}
}
}
}
/**
* 添加消息到控件
*/
private fun addMsg2View(roomMsg: String) {
var currentMsg = mainBinding.tvChat.text.toString()
if(TextUtils.isEmpty(currentMsg)){
mainBinding.tvChat.text = "$roomMsg"
}else{
mainBinding.tvChat.text = "$currentMsg \n $roomMsg"
}
}
}