我是web套接字编程的新手。。。
我有以下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"
在GlassFish服务器日志上,我得到了"ping"one_answers"Websocket客户端",但在onopen事件退出后连接关闭(不确定),因此,日志上没有出现最后一个单词"finish",错误发生了。
我想知道我的代码是否正确
错误的原因是什么?javascript代码、GlassFish服务器配置还是java端点代码?
尝试更改glassfish 8080端口,例如:8887,或者确保您的防病毒/其他应用程序没有使用端口80,我以前遇到过我的服务器websocket被使用端口80的防病毒软件阻止的情况。