我是WebSocket Java开发的新手,我有一个包含服务的会话bean:
@Stateless
@LocalBean
public class TransferService implements TransferServiceLocal {
@Inject
private Event<PushNotification> notificationEvent;
@PersistenceContext
private EntityManager em;
private PushNotification createNotification(Integer userId, String title,
String message) {
PushNotification pushNotification = new PushNotification();
pushNotification.setUserId(userId);
pushNotification.setTitle(title);
pushNotification.setMessage(message);
pushNotification.setDcr(new Date());
// Notify the observers about the new push notification
notificationEvent.fire(pushNotification);
return pushNotification;
}
@Override
public void addTransfer(Transfer transfer) {
em.persist(createNotification(visitor.getId(), "New Task", "You have new task"));
em.persist(transfer);
}
}
我希望当我在EntityManager上创建一个新的persist时,会发送一个从websocket到客户端的新通知,问题是fire事件无法正常工作!!
以及我在WebSocket POJO中的内容:
import javax.enterprise.event.Observes;
import javax.websocket.server.ServerEndpoint;
import persistence.PushNotification;
@ServerEndpoint("/testws")
public class TestEndpoint {
private SessionRegistry sessionRegistry;
public void send(@Observes PushNotification notification) throws IOException{
Set<Session> sessions = sessionRegistry.getAll();
for (Session session : sessions) {
session.getBasicRemote().sendText(toJson(notification));
}
System.out.println("new notification, message : "
+ notification.getMessage());
}
private String toJson(PushNotification notification) {
final JsonObject jsonObject = Json.createObjectBuilder()
.add("id", notification.getId())
.add("message", notification.getMessage()).build();
return jsonObject.toString();
}
}
我的代码出了什么问题请在最后两天遇到这个问题并且仍然困惑:(