WebRTC:搭建Socket.Io信令服务器(实现简单的聊天室
2022-04-11 本文已影响0人
itfitness
目录
效果展示
实现步骤
1.搭建服务端
这里我们用的是nodejs搭建的,由于我们用的不是最新标准的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);
//通知某设备加入房间
sokcetClient.in(roomId).emit('joined', roomId, sokcetClient.id);
});
sokcetClient.on('leave', (roomId) => {
//离开房间
sokcetClient.leave(roomId);
//通知某设备离开房间
sokcetClient.in(roomId).emit('leaved', roomId, sokcetClient.id);
});
sokcetClient.on('sendRoomMsg',(roomId,msg)=>{
//向房间内推送消息
sokcetClient.in(roomId).emit('receiveRoomMsg', msg);
})
});
其中socket.io中部分常用的函数及左右如下:
on:用于监听对应的事件,接收的参数取决于emit发送的数据
emit:用于发送相应的事件
in(roomId).emit:用于在相应的房间内发送事件
join(roomId):加入相应的房间
leave(roomId):离开相应的房间
2.客户端实现
1.引入依赖
https://socketio.github.io/socket.io-client-java/installation.html
这里由于服务器不是使用的最新的socketio,因此我们客户端也引入1.0.0版本的库
implementation ('io.socket:socket.io-client:1.0.0') {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
2.代码实现
<?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="断开连接"
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="发送消息"
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" //房间号
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 {
//发送离开事件
it.emit("leave",roomId)
it.disconnect()
it.close()
}
}
mainBinding.btJoinroom.setOnClickListener {
socket?.let {
//发送加入事件
it.emit("join",roomId)
}
}
mainBinding.btSendmsg.setOnClickListener {
var msg = mainBinding.etSendmsg.text.toString()
//发送消息就是发送sendRoomMsg事件,然后服务器会进行转发
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事件用于对房间消息的显示
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"
}
}
}