lukeed / sockette

The cutest little WebSocket wrapper! 🧦
MIT License
2.45k stars 81 forks source link

When I close the connection, it doesn't send queryStringParameters #56

Closed kyun closed 4 years ago

kyun commented 4 years ago

I built up the WebSocket server with AWS API Gateway.

and, I am connecting this with AWS Lambda.

It works well when I connect, but when I disconnect, it doesn't work well.

My React Client Code

import React from 'react';

function socketHandler(uid){
  const wss = new Sockette(`wss://MY_API_GATEWAY_URL.execute-api.ap-northeast-2.amazonaws.com/dev?groupId=GROUP_ID&uid=${uid}`, {
    timeout: 1000,
    maxAttempts: 10,
    onopen: (e: any) => { console.log(e); console.log('Websocket is connected') },
    onmessage: (e: any) => {
      console.log(e.data);
    },
    onclose: (e: any) => { console.log(e); console.log('Websocket is disconnected'); }
  });
  return wss;
}

const SocketForm = (props) => {
  const [socket, setSocket] = React.useState(null);

  React.useEffect(()=> {
    setSocket(socketHandler(`MY_UID`);
  }, []);
  const socketDisconnect = () => {
    socket.close();
  }
  return (
    <div> 
      <button onClick={socketDisconnect}>Disconnect</button>
    </div>
  )
}

My Lambda Code

 /* it works well when I connect. */
export const socketHandler = async (evt) => {
  const {groupId, uid} = evt.queryStringParameters; // When I disconnect it occurs ERROR.

   /* Skip Saving connectionId */

   return { statusCode: 200, body: JSON.stringify({}) };
};

I'd like to use WebSocket URL withqueryParameters even I disconnect.

If I missed something, please reply me.

lukeed commented 4 years ago

Hey,

I think you may be missing something with your AWS Lambda code. Generally, disconnect happens in a separate handler, but I'm not sure what exactly you're doing.

In any event, on the client-side, what Sockette does is exactly the same as the following code:

function socketHandler(uid){
  const url = `wss://MY_API_GATEWAY_URL.execute-api.ap-northeast-2.amazonaws.com/dev?groupId=GROUP_ID&uid=${uid}`;
  return new WebSocket(url);
}

const wss = socketHandler('123');

setTimeout(() => {
  // some time later...
  wss.close(1000);
}, 3000);

Sockette doesn't add/change anything in this process; see here

If the above still fails for you, either your Lambda code needs adjusting or the browser API doesn't do what you're expecting – which, IMO, still means that your Lambda needs adjusting.

Hope that helps! Keep me posted