スレッド内で実行されているudpサーバに、データグラムを受信するたびにイベントを発生させ、jsonという形式のデータを送信します。実際にイベントを発生させますサーバで実行中のスレッドからCDIイベントを起動するにはどうすればよいですか?
public class StatusChangeObserver {
public void statusChanged(@Observes StatusChange sce) {
WebsocketEndPoint.sendAll(sce.getJson());
}
}
@ServerEndpoint(value="/websocket")
public class WebsocketEndPoint {
private static Set<Session> userSessions = Collections.synchronizedSet(new HashSet<Session>());
@OnOpen
public void onOpen(Session userSession) {
System.out.println("Opening new connection");
userSessions.add(userSession);
}
@OnClose
public void onClose(Session userSession) {
System.out.println("Connection closed. Id: " + userSession.getId());
userSessions.remove(userSession);
}
public static void sendAll(String message) {
for (Session session : userSessions) {
if (session.isOpen()) {
session.getAsyncRemote().sendText(message);
}
}
}
}
ハンドラ:
public class UDPServer extends Thread {
private SocketUDPCommunication comm;
@Inject @Notify
private StatusChangeHandler sch;
public UDPServer() {
comm = new SocketUDPCommunication();
}
@Override
public void run() {
DatagramPacket response;
comm.setPort(Utils.UDP_SERVER_PORT);
comm.createSocket();
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Waiting for clients to connect on port:" + comm.getSocket().getLocalPort());
try {
response = comm.receiveResponse();
} catch (SocketTimeoutException e) {
continue;
}
byte[] byteSend = comm.discardOffset(response);
Status status = frameToJson(byteSend);
Genson genson = new Genson();
String json = genson.serialize(status);
sch.sendChangedStatus(json); //Raise the cdi event, sch not initialized!!
}
}
@Override
public void interrupt() {
super.interrupt();
comm.closeConnection();
}
}
が接続されているすべてのクライアントにこのメッセージをブロードキャストするのWebSocketエンドポイントのメソッドを呼び出します。このイベントのリスナーを、そこに定義されます
@Notify
public class StatusChangeHandler {
@Inject
private Event<StatusChange> statusChangedEvent;
public void sendChangedStatus(String json) {
StatusChange sce = new StatusChange(json);
statusChangedEvent.fire(sce);
}
}
StatusChange
は、ブロードキャストするメッセージを含む単純なPOJOです。 @Notify
修飾子:
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface Notify {
}
これらは依存性注入との私の最初のステップですので、私は、私は、スレッド内からイベントを発生する方法、およびsch
オブジェクトを初期化する方法をかなりよく分かりません。 Weld
とWeldContainer
クラスを使用してCDIを初期化することをお勧めするthis pageが見つかりましたが、このクラスをmavenで見つけることができません。これは正しいアプローチですか?その場合、誰も私のプロジェクトにこれらのクラスを含める方法を知っていますか?
Tomcatにデプロイする場合は、Weld Servletの代わりにWeld Servlet https://docs.jboss.org/weld/reference/latest/en-US/html/environments.html#weld-servletを使用する必要があります。溶接SE。 –