I am building my app:
Frontend: ReactJS / Javascript Native Websocket: In my component that uses websocket:
useEffect(() => {
const orgId = localData.get('currentOrganizationId');
const username = localData.get('username');
let socket = new WebSocket(process.env.REACT_APP_WEBSOCKET_URL); // this is the AWS WebSocket URL after I have deployed it.
// let socket = new WebSocket("ws://127.0.0.1:3001");
socket.onopen = function(e) {
console.log('socket on onopen');
const info = JSON.stringify({orgId:orgId, username: username, action: "message"});
socket.send(info);
};
socket.onmessage = function(event) {
console.log(`[message] Data received from server: ${event.data}`);
};
socket.onclose = function(event) {
if (event.wasClean) {
console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
console.log(`[close] Connection died; code=${event.code}`);
}
};
socket.onerror = function(error) {
console.log(`[error] ${error.message}`);
};
}, [])
Backend: NodeJS / ExpressJS / ws websocket library:
./utils/websocket:
import WebSocket from "ws";
import queryString from "query-string";
import { StateManager } from '../state';
import logger from '../logger';
export default async (expressServer) => {
StateManager.addToState('sockets', {});
const websocketServer = new WebSocket.Server({
noServer: true,
// path: "/websockets",
path: "/",
});
expressServer.on("upgrade", (request, socket, head) => {
logger.info(`on upgrade: ${JSON.stringify(head)}`);
websocketServer.handleUpgrade(request, socket, head, (websocket) => {
websocketServer.emit("connection", websocket, request);
});
});
websocketServer.on("connection", function connection(websocketConnection, connectionRequest) {
logger.info(`on connection`);
websocketConnection.on("message", (message) => {
const info = JSON.parse(message);
logger.info(`info: ${typeof info} ${info}`);
const sockets = StateManager.readFromState('sockets');
sockets[info.username] = websocketConnection;
});
});
return websocketServer;
};
and in index.ts:
import websocket from './utils/websocket';
...other code
const app = express();
...other code
const server = app.listen(parseInt(process.env.PORT) || 3001);
websocket(server);
While this works well in local dev environment, I am really confused on how to move this to AWS like this:
Frontend WebSocket client ---> AWS API Gateway Websocket API ----> Backend in EC2 instance
I have read the document, but I am still confused about where to start. How should I configure the $connect, $disconnect, $default routes?
How are they related to my current websocket client and nodejs server running in EC2?
How should I change the code to integrate it with AWS API Gateway Websocket API?
Currently there is simply no response:

The Websocket URL I provided is indeed correct though.
Even after reading the document, I am still confused about where to start fixing this issue.

