Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

Android Kotlin - Socket Server to handle Multiple Clients

I am creating a Socket music game using Kotlin in android, right now I have a 1 on 1 functioning app that does all I want it to, but I want to be able to support multiple clients(4 max), how should I refactor my code to do this? , should I be using coroutines or Threads? , the server sends a song to each client every 30 seconds so I would ideally like a way to send the same message to each client with minor delay

Server

                    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

                        }

Client

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)
}
}

Any help would be much appreciated!

question from:https://stackoverflow.com/questions/65892895/android-kotlin-socket-server-to-handle-multiple-clients

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...