是否可以先创建WebSocket对象,然后创建设置处理程序,最后创建连接?

时间:2019-02-13 13:53:21

标签: websocket ws isomorphic-ws

当前,我的代码如下所示,因为在调用WebSocket构造函数时会启动WebSocket连接。

import WebSocket = require('isomorphic-ws');

let socket = new WebSocket(`${host}:${port}`);
socket.onerror = (event: { error: any }): void => {
    console.log('good');
};
socket.onopen = (): void => {
    console.log('bad');
};

这让我感到有些混乱。是否可以重写此代码,以便首先创建WebSocket对象,然后创建设置处理程序,最后创建连接?像这样:

import WebSocket = require('isomorphic-ws');

let socket = new WebSocket(`${host}:${port}`);
socket.onerror = (event: { error: any }): void => {
    console.log('good');
};
socket.onopen = (): void => {
    console.log('bad');
};
socket.connect();

0 个答案:

没有答案