WebSocket Web客户端在与wss连接时获得1006

yrwegjxp  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(277)

我有一个WebSocket node.js服务器,并成功地从ios,android连接。但是,在angular web应用程序中使用rxjs/WebSocket连接时失败,返回1006。
然后我在本地运行WebSocket服务器,将localhost:4200 angular Web应用程序与服务器连接-> ws://localhost:3000/ws,它工作正常。为什么不能与wss一连接。
伺服器:

const app = express();
const server = createServer(app);
const cors = require('cors');

app.use("/", express.static("public"));
var corsOptions = {
  origin: 'http://localhost:4200',
  credentials: true
};
app.use(cors(corsOptions));

const wsApp = expressWs(app, server).app;
wsApp.ws("/ws", handleSocketConnection);

const port = process.env.PORT || 3000;
server.listen(port, () => {
  console.log(`server started on http://localhost:${port}`);
});

委托方:

public initSocket(clientId): void {
    console.log('init socket');
    this.socket = webSocket(environment.webSocket);

    this.socket.next({ "channel": "login", "name": clientId });

}

public getMessage(): Observable<IWebsocketMessage> {
    return new Observable<IWebsocketMessage>(observer => {
        this.socket.subscribe((data: IWebsocketMessage) => {
            console.log('message received: ' + JSON.stringify(data));
            observer.next(data);
        }, error => {
            console.log(error);
        });

    });
    //    return this.socket.asObservable();
}
vlf7wbxs

vlf7wbxs1#

//Below is reactjs code that is working for a chat message app

var socket = new WebSocket('wss://your_socket_url/ws');
 
useEffect(() => { 
    connect();
    return () => {
      disconnect();
    }

  }, []);
 

  function disconnect() {

    clearInterval(reconnectInterval);
    socket.close();
  }

  function connect() {

    socket.onopen = (event) => {

      clearInterval(reconnectInterval);

      socket.send(JSON.stringify({
        channel: 'login',
        name: getUserId(),
      }));

    };

    socket.onmessage = (event) => {
      const json = JSON.parse(event.data);
      //add your logic 
    };

    socket.onclose = (event) => {

      reconnectInterval = setInterval(
        () => {
          reconnect();
        },
        1000,
      )
      // console.log('Socket is closed. Reconnect will be attempted in 1 second.', event);

    };

    socket.onerror = (err) => {

      clearInterval(reconnectInterval);

      console.error('Socket encountered error: ', err, 'Closing socket');
      socket.close();
    };

    function reconnect() {

      if (socket.readyState != WebSocket.CONNECTING) {
        socket = new WebSocket('wss://your_socket_url/ws');
        connect();
      }
    }
  }

相关问题