Viewmodel
unknown
kotlin
3 years ago
3.4 kB
26
Indexable
package pt.isec.tp2223g3.g3mathgame.multiplayer
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import org.json.JSONObject
import pt.isec.tp2223g3.g3mathgame.singleplayer.countdown.GameStates
import java.io.*
import java.net.ServerSocket
import java.net.Socket
import kotlin.concurrent.thread
class MultiplayerGameViewModel : ViewModel() {
private var sockets = arrayListOf<Socket>()
private var threadsComms = arrayListOf<Thread>()
private var numPlayers = 0
private var index : Int = -1
private var serverSocket : ServerSocket? = null
private var keepGoing = true
private val PORT = 9999
private val _connectionState = MutableLiveData(ConnectionStates.SETTING_PARAMETERS)
val connectionState : LiveData<ConnectionStates>
get() = _connectionState
private val _gameState = MutableLiveData(GameStates.WAITING)
val gameState : LiveData<GameStates>
get() = _gameState
fun startServer(){
if(serverSocket != null || sockets.isNotEmpty() || _connectionState.value != ConnectionStates.SETTING_PARAMETERS)
return
_connectionState.postValue(ConnectionStates.SERVER_CONNECTING)
serverSocket = ServerSocket(PORT)
thread{
while(keepGoing) {
serverSocket?.run{
try{
val socket = serverSocket!!.accept()
Log.i("DEBUG", "Client connected")
updateInfo(socket)
threadsComms.add(thread {
_connectionState.postValue(ConnectionStates.CONNECTION_ESTABLISHED)
val reader = BufferedReader(InputStreamReader(socket.getInputStream()))
val writer = PrintWriter(socket.getOutputStream())
val buffer = reader.readLine()
val data = JSONObject(buffer)
Log.i("DEBUG", data.toString())
})
}
catch (_: Exception){
stopServer()
}
}
}
}
}
private fun updateInfo(socket: Socket){
sockets.add(socket)
index++
numPlayers++
}
private fun stopServer(){
serverSocket?.close()
_connectionState.postValue(ConnectionStates.CONNECTION_ENDED)
serverSocket = null
}
fun stopGame(){
try {
_gameState.postValue(GameStates.GAME_OVER)
_connectionState.postValue(ConnectionStates.CONNECTION_ERROR)
val itSockets = sockets.iterator()
val itThread = threadsComms.iterator()
while(itSockets.hasNext()) {
val socket = itSockets.next()
socket.close()
sockets.remove(socket)
}
while(itThread.hasNext()){
val thread = itThread.next()
thread.interrupt()
threadsComms.remove(thread)
}
}catch (_:java.lang.Exception){ }
}
}Editor is loading...