2014-10-05 229 views
1

我是新手到網絡套接字編程...Websocket連接自動關閉?

,我有以下的JavaScript客戶端代碼:

var connection = new WebSocket('ws://localhost:8080/OmegaThings/registerdevice'); 

     connection.onopen = function() {    
      console.log("Socket has been opened state = " + connection.readyState); 
      connection.send('Ping'); // Send the message 'Ping' to the server    
      connection.send('Websocket client'); 
     }; 

     console.log("Socket has been opened state = " + connection.readyState); 
     connection.send('finish'); 

     // Log errors 
     connection.onerror = function (error) { 
     console.log('WebSocket Error ' + error); 
     }; 

     // Log messages from the server 
     connection.onmessage = function (e) { 
     console.log('Server: ' + e.data); 
     }; 

Java的端點:

@ServerEndpoint("/registerdevice") 
public class RegisterDeviceEndPoint 
{ 
    private static final Logger LOG = Logger.getLogger(RegisterDeviceEndPoint.class.getName()); 

    @OnOpen 
    public void connectionOpened() 
    {  
     LOG.log(Level.INFO, "******************connection opened**************"); 
    } 

    @OnMessage 
    public synchronized void processMessage(Session session, String message) 
    {  
     LOG.log(Level.INFO, "received message: {0}", message); 
    } 

    @OnClose 
    public void connectionClosed() 
    {  
     LOG.log(Level.INFO, "connection closed"); 
    } 
} 

Firefox的控制檯我上以下輸出:

"Socket has been opened state = 1" 
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable 
"Socket has been opened state = 0" 

on GlassFish s erver日誌我得到了「ping」和「Websocket客戶端」,但是在onopen事件退出(不確定)後關閉連接,因此最後一個字詞「finish」沒有出現在日誌中,並且發生錯誤。

我想知道我的代碼是否正確?
什麼原因導致錯誤? JavaScript代碼,GlassFish服務器配置還是Java端點代碼?

+0

我想你刷新了可能終止現有連接的頁面。可能是這個鏈接將幫助你http://stackoverflow.com/questions/21675247/websocket-maintain-user-session-after-page-reloading – mallikarjun 2014-10-05 17:07:52

回答

0

我通過以下this tutorial解決了這個問題,無論如何,我不知道確切的問題,但它的作品..!

-1

嘗試更改GlassFish的8080端口,如:8887,或請確保您的防病毒/其它應用未使用端口80,我以前有經驗,在我的服務器的WebSocket被反病毒使用哪個端口80

相關問題