首页 > 解决方案 > Android Kotlin - 处理多个客户端的套接字服务器

问题描述

我正在使用 android 中的 Kotlin 创建一个 Socket 音乐游戏,现在我有一个 1 对 1 功能的应用程序可以满足我的所有需求,但我希望能够支持多个客户端(最多 4 个),我应该如何重构我的代码做到这一点?,我应该使用协程还是线程?,服务器每 30 秒向每个客户端发送一首歌曲,所以理想情况下,我希望有一种方法可以向每个客户端发送相同的消息,但延迟很小

服务器

                    val server = ServerSocket(6000)
                    Log.i("Server","Opening Connection on ${server.localPort}")
                    val client = server.accept()
                    Log.i("Server","Client Connected")
                    output = PrintWriter(client.getOutputStream(), true)
                    var input = BufferedReader(InputStreamReader(client.inputStream))


                    output.println(j_song.toString())

                   
                    // Sending each song in a playlist to all clients
                    for(i in songs)
                    {
                        val send_song = Gson().toJson(i)
                        output.println(send_song)
                        val status = input.readLine()
                         // Other functionality

                        }

客户

GlobalScope.launch {
           socket = Socket("10.0.2.2", 5000)
           output = PrintWriter(socket.getOutputStream(), true)
           input = BufferedReader(InputStreamReader(socket.getInputStream()))
           Log.i("Client Connected", "Connected to Server ${socket.inetAddress.hostAddress}")
           val mes = input.readLine()
           Log.i("Client", mes)

           val songs = JSONArray(mes)
           Log.i("Client (JSON LIST)", songs.toString())

         
           
           var server_song : String
           while(true)
           {

                server_song = input.readLine()
                output.println(status)
}
}

任何帮助将非常感激!

标签: androidsocketskotlin

解决方案


推荐阅读