WebRTC:搭建Socket.Io信令服务器(实现简单的谈天室)

源代码 2024-9-20 16:03:21 14 0 来自 中国
目次

效果展示

2.gif 实现步骤

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        androidrientation="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"        }    }}
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 20:20, Processed in 0.171581 second(s), 35 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表