private fun receiveVideoFromServer() {
GlobalScope.launch(Dispatchers.IO) {
var socket: Socket? = null
try {
// Replace placeholders with server details
val host = "192.168.0.34" // YOUR ACTUAL SERVER IP
val port = 12345 // YOUR ACTUAL SERVER PORT
// Choose a suitable save directory and file path
val directory = requireNotNull(externalCacheDir) {
Log.e("VideoReceiveError", "External cache directory is null")
return@launch // Gracefully handle the error
}
// Connect to server
socket = Socket()
socket.connect(InetSocketAddress(host, port), 200000)
var filecount = 0
while(filecount<12) {
val saveFilePath = File(directory, "video$filecount.mp4") // Change if needed
// Input stream for reading video data
val inputStream = socket.getInputStream()
// val inputStream = BufferedInputStream(socket.getInputStream())
// Create output stream for saving the video
val fileOutputStream = FileOutputStream(saveFilePath)
// Receive and write video data in chunks
val buffer = ByteArray(1024)
var bytesRead: Int
while (inputStream.read(buffer).also { bytesRead = it } != -1) {
fileOutputStream.write(buffer, 0, bytesRead)
}
// Finish writing and close streams
fileOutputStream.close()
// Success message and optional video playback (use a suitable video player library)
withContext(Dispatchers.Main) {
Toast.makeText(
this@MainActivity,
"Video received successfully: $saveFilePath",
Toast.LENGTH_SHORT
).show()
Log.d("ReciveSucc", "Video received successfully: $saveFilePath")
// ... Play video
}
filecount++
}
} catch (e: Exception) {
// Handle network errors, connection failures, and other exceptions
Log.e("VideoReceiveError", "Error receiving video: ${e.message}", e)
withContext(Dispatchers.Main) {
Toast.makeText(this@MainActivity, "Error receiving video", Toast.LENGTH_SHORT)
.show()
}
} finally {
// Close socket gracefully
try {
socket?.close()
} catch (e: IOException) {
Log.e("SocketCloseError", "Error closing socket: ${e.message}", e)
}
}
}
}
In this given code i am not abele to receive multiples files from the server,Problem is when first file is recive succesfully and after other files are coming 0Bytes and continues coming,and server send only 12 files.Server is Raspberry pi and my phone work as client and server send all files.
I am try to receve all file completly.