我想知道是否有一种使用DatagramPacket的UDP消息的OnMessage()类型功能?我希望能够确保在收到所有邮件时收到所有邮件,这样我就不会浪费资源随意抓住计时器。
OnMessage我指的是在WebSocketClient中完成的那个。或者某些功能类似于"可用"在.net。
While (rxUdpClient.Available > 0)
我正在监视多个端口,因此调用一个线程,该线程将为每个端口执行run()。问题是我似乎有40 + /秒的巨大速度消息。
这就是我目前所拥有的:
public void run()
{
DatagramSocket sock = null;
sock = new DatagramSocket(port);
byte[] buffer = new byte[DataAdapterFB1.HEADER_SIZE + DataAdapterFB1.MAX_DATA_BYTES];
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
while (true){
sock.receive(incoming);
byte[] data = incoming.getData();
String s = new String(data, 0, incoming.getLength());
//This is the processing code, but it isn't its own thread...
ScadaMsg newMessage = new ScadaMsg(data);
}
}
答案 0 :(得分:1)
DatagramPacket receive()操作是阻塞的,所以你通常会做的就是启动一个单独的线程,它将在循环中侦听传入的数据报并将它们分派给进一步处理,就像那样:
void run() {
socket = new DatagramSocket(4445);
while(true) {
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet); //JVM will wait here, until there is an incoming packet
onMessage(packet.getData())
}
}
public abstract void onMessage(final byte[] pkt);