2014-03-13 140 views
1

我有以下代碼發送推送通知到瀏覽器,一旦我運行應用程序獲得EJB開始,在控制檯它顯示超時,發送等的WebSocket是無法建立連接

但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> 
+0

你在服務器上使用了什麼庫? –

+0

@ user2310289我使用javax.websocket-API 1.0 – AlexCartio1

+0

你的會話中添加對'onOpen'我看不到這個代碼隊列中。 –

回答

0

當你部署

<dependency> 
    <groupId>javax.websocket</groupId> 
    <artifactId>javax.websocket-api</artifactId> 
    <version>1.0</version> 
    <scope>provided</scope> 
</dependency> 

使這個規定。