Writing a websocket client to connect to remote websocket server doesn't work

I am trying to connect to a remote websocket server from the worker, so worker is the websocket client and remote websocket is the server.

I just did just the documentation describes (https://developers.cloudflare.com/workers/learning/using-websockets/#connecting-to-the-websocket-server-from-a-client) but I get errors as below.

My code:

let targetSocket = new WebSocket(targetWebSocketServerURL)
if (!targetSocket) {
throw new Error("server didn't accept WebSocket");
targetSocket.send("PING")

I get “You must call accept() on this WebSocket before sending messages.”

and when I add “targetSocket.accept()” it says
"Websockets obtained from the ‘new WebSocket()’ constructor cannot call accept
at handleRequest "

any help on how to resolve this would be appreciated

Running into the same issue.

I’m also having the same issue.

Workaround is to use the fetch then upgrade trick in the documentation.

let {webSocket:targetSocket} = await fetch(
  targetWebSocketServerURL,
  {headers: {Upgrade: 'websocket'}}
);