Hi,
I need a helping hand, can somebody explain why the event does not fire?
THX
I need a helping hand, can somebody explain why the event does not fire?
THX
B4X:
package com.socket;
import anywheresoftware.b4a.BA.Events;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.*;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Events(values={"packetreceived (message() As Byte,ipaddress as String,len as int,Myip as string)"})
@Version(0.2f)
@ShortName("Multicast")
public class Wrapper {
private BA baevent;
private String _eventName;
private MulticastSocket _socket;
private ExecutorService _executor = Executors.newSingleThreadExecutor();
private volatile boolean _shouldReceive = true;
public void initialize(final BA ba, final String eventName, final int port, final String host) throws Exception {
baevent = ba;
final InetAddress ip = InetAddress.getByName(host);
_socket = new MulticastSocket(port);
_socket.joinGroup(ip);
_executor.execute(this::receiveLoop);
}
public void close() throws IOException {
try {
_shouldReceive = false;
_executor.shutdownNow();
} finally {
_socket.close();
}
}
private void receiveLoop() {
try {
final byte[] receiveData = new byte[188]; // Get one TS packet from stream
final DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
while (_shouldReceive && !Thread.interrupted()) {
_socket.receive(receivePacket);
if (receivePacket.getLength() > 0) {
final String sourceHost = receivePacket.getAddress().getHostAddress();
//System.out.println("message: " + new String(receivePacket.getData(), StandardCharsets.UTF_8));
baevent.raiseEventFromDifferentThread(this, null, 0, _eventName + "_packetreceived", false, new Object[]{receivePacket.getData(), sourceHost, receivePacket.getLength() });
}
}
} catch (final IOException e) {
e.printStackTrace();
}
}
}
Last edited: