android - 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)
}
}
任何帮助将非常感激!
解决方案
推荐阅读
- python - 多种功能输出的良好设计模式
- vue.js - 如何根据 v-for 中的键更改样式?
- apache-nifi - 无法从 sql server 表中获取记录
- php - 如何解决 Doctrine 中的多对一关系中的重复条目?
- oracle - 外部表 - 用数字中的点替换逗号
- php - 我的代码中的函数 set_title() 有什么问题
- javascript - 从角度组件订阅扩展 .ts 文件时返回成功数据
- python - TIC TAC TOE 两个人类玩家,Python
- javascript - NodeJs API 在转换较大文件时发送空白响应
- excel - 如何根据 3 列的值有条件地格式化范围