У меня есть следующий код для отправки push-уведомлений в браузер, как только я запустил приложение, запустите EJB и в консоли он отобразится в тайм-аут, отправьте и т.д.
Но Firefox показывает, что не удалось установить соединение с сервером по адресу ws://localhost: 8080/Notifications.
Функция JavaScript
<script type="text/javascript">
var wsocket;
function connect() {
wsocket = new WebSocket("ws://localhost:8080/Notifications");
alert("got connected");
wsocket.onmessage = onMessage;
}
function onMessage(evt) {
alert(evt);
var arraypv = evt;
alert("array" + arraypv);
document.getElementById("foo").innerHTML = arraypv[0];
}
alert("window" + connect);
window.addEventListener("load", connect, false);
</script>
Отображение Struts
<action name="Notifications" class="com.example.controller.Notifications">
</action>
Класс уведомлений
@ServerEndpoint("/Notifications")
public class Notifications {
static Queue<Session> queue = new ConcurrentLinkedQueue();
public static void send() {
System.err.println("send");
String msg = "Here is the message";
try {
/* Send updates to all open WebSocket sessions */
for (Session session : queue) {
session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@OnOpen
public void openConnection(Session session) {
System.err.println("in open connection");
queue.add(session);
}
@OnClose
public void closedConnection(Session session) {
System.err.println("in closed connection");
queue.remove(session);
}
@OnError
public void error(Session session, Throwable t) {
System.err.println("in error");
queue.remove(session);
}
Класс PriceVolumeBean
@Startup
@Singleton
public class PriceVolumeBean {
@Resource TimerService tservice;
private Random random;
@PostConstruct
public void init() {
System.err.println("in init");
random = new Random();
tservice.createIntervalTimer(1000, 1000, new TimerConfig());
}
@Timeout
public void timeout() {
System.err.println("in timeout");
Notifications.send();
}
}
pom.xml
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
</dependency>
при развертывании
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
сделайте это.