【问题标题】:Websocket connection closed automatically?Websocket连接自动关闭?
【发布时间】:2023-03-03 19:45:01
【问题描述】:

我是 web-socket 编程的新手...

我有以下 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”和“Websocket 客户端”,但是在 onopen 事件退出后连接关闭(不确定),因此,最后一个单词“finish”没有出现在日志上并且错误发生。

我想知道我的代码是否正确?
是什么导致错误? javascript 代码、GlassFish 服务器配置还是 java 端点代码?

【问题讨论】:

标签: java javascript jakarta-ee websocket glassfish


【解决方案1】:

尝试更改 glassfish 8080 端口,例如:8887,或确保您的防病毒/其他应用程序未使用端口 80,我之前有过使用端口 80 的防病毒软件阻止我的服务器 websocket 的经验。

【讨论】:

    猜你喜欢
    • 2012-02-21
    • 2020-08-10
    • 1970-01-01
    • 2019-10-22
    • 2012-08-08
    • 2016-05-15
    • 1970-01-01
    • 2016-12-08
    • 2019-09-18
    相关资源
    最近更新 更多