简体   繁体   English

在JS API中并为JS API建立WebSocket连接

[英]Establishing WebSocket Connection within and for a JS API

Aim: In order to provide a simple, easy-to-use JS library that communicates with a server I am trying to establish a WebSocket connection at the start of my API and define the library's functionality thereafter. 目的:为了提供一个与服务器通信的简单易用的JS库,我试图在API的开头建立一个WebSocket连接,并在此后定义该库的功能。

Problem: The issue is that my socket's readystate does not transition to 1 (ready) before the library is loaded and the user's script is run. 问题:问题是在加载库和运行用户脚本之前,我的套接字的ready状态没有转换为1(就绪)。 Debugging this has confirmed this and I'm not sure how to ensure my WebSocket is established before proceeding with the user's script. 对此进行调试已经确认了这一点,我不确定在继续执行用户脚本之前如何确保WebSocket已建立。

What I have: 我有的:

(function(myObject) {

var socket = new WebSocket(url);

socket.emit = function() {
    //do some tasks and create a var "message"
    socket.send(message);
}

window.myObject = myObject.prototype = {
    doSomething: function() {
        socket.emit();  
    }
}

}(myObject = window.myObject || {}));

Above, I've defined a custom method (socket.emit()) on the socket object that, in turn, calls socket.send(). 上面,我在套接字对象上定义了一个自定义方法(socket.emit()),该方法又调用socket.send()。 I do this to manipulate some data before sending it via socket.send(), reusing code that would otherwise be repeated. 我这样做是为了在通过socket.send()发送数据之前处理一些数据,重用了否则会重复的代码。

Then I have some very basic html that includes this JS library and a simple script runs as follows: 然后,我有了一些非常基本的html,其中包括此JS库,并且一个简单的脚本运行如下:

$(document).ready(function() {
    myObject.doSomething();
});

The error I get is: "Failed to execute 'send' on 'Websocket': already in CONNECTING state." 我得到的错误是:“无法在'Websocket'上执行'发送':已经处于CONNECTING状态。”

The library successfully loads but the Websocket does not complete connection before the client script is run. 库成功加载,但Websocket在运行客户端脚本之前未完成连接。 How can I ensure my WebSocket is connected (readystate == 1) before the API finishes loading? 如何在API完成加载之前确保WebSocket已连接(readystate == 1)?

Thanks for the help! 谢谢您的帮助!

What you could do is buffer all messages in socket.emit as long as the socket is not connected and send them once you receive the onOpen callback. 只要套接字未连接,就可以将所有消息缓冲在socket.emit ,并在收到onOpen回调后将其发送。

While this will handle your current problem you will see that new ones will arise: You might want to handle disconnects from your server and reconnects and therefore you might need to extend your library API anyhow to also expose connectionstate change events and force the library user to only send messages when connected. 尽管这将解决您当前的问题,但您会看到新的问题:您可能希望处理与服务器的断开连接并重新连接,因此,您可能无论如何都需要扩展库API来公开连接状态更改事件并强制库用户执行以下操作:仅在连接时发送消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM