我是新手到網絡套接字編程...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端點代碼?
我想你刷新了可能終止現有連接的頁面。可能是這個鏈接將幫助你http://stackoverflow.com/questions/21675247/websocket-maintain-user-session-after-page-reloading – mallikarjun 2014-10-05 17:07:52