Answer the question
In order to leave comments, you need to log in
UDP socket in android. What to choose NIO or IO? And how to figure it out?
Hello!
Didn't find any good answers on this topic.
At the moment, sockets are used to interact with the hardware. I create a socket (DatagramSocket) on one port I need (you can choose a random one), all further operations must be performed from this port. The timeout is set to 1 second. In all other parts (other threads) I pass exactly this created socket instance.
I interact with them in the following ways:
import android.os.Handler
import android.os.Message
import com.controller.labaratory.controller.App
import com.controller.labaratory.controller.models.Container
import java.net.*
/**
* Created by ivan on 03/08/17.
*/
class DataPacketThread(val handler: Handler,
val socket: DatagramSocket,
val addres: InetAddress):Thread() {
override fun run() {
super.run()
while (!socket.isClosed){
try{
//socket.soTimeout=0
var buffer:ByteArray = kotlin.ByteArray(1024)
val packet = DatagramPacket(buffer, buffer.size)
socket?.receive(packet)
val odin:Byte = -1
if (!(buffer[0] == odin)){
if(packet.data[0].toInt() == 4){
val responseByteArray:ByteArray = byteArrayOf(1,33,
packet.data[2],packet.data[3])
val packetResponseAnswer = DatagramPacket(responseByteArray,
responseByteArray.size, addres, 1026)
socket?.send(packetResponseAnswer)
handler?.sendMessage(
Message.obtain(
handler,
App.UdpClientHandler.DATA_PACKET_RECEIVE,
HandlerContainer(825, Container(
packet.length,
packet.data))))
}
}
} catch (e:SocketTimeoutException){
e.printStackTrace()
} catch (e:SocketException){
e.printStackTrace()
}
}
}
fun end(){
socket.close()
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question