Server

mail@pastecode.io avatar
unknown
kotlin
2 years ago
1.4 kB
9
Indexable
Never
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())
                            while(keepGoing){
                                val data = reader.readLine()
                                Log.i("DEBUG", "Received data")
                                Log.i("DEBUG", data.toString())
                            }
                        })
                    }
                    catch (_: Exception){
                        stopServer()
                    }
                }
            }
        }
    }