To close a WebSocket connection with JavaScript, you can use the close()
method provided by the WebSocket object.
To do this, we write:
// Assuming 'ws' is your WebSocket object
ws.close();
This code will close the WebSocket connection gracefully. If you need to handle the closure event or provide a reason for closure, you can pass optional parameters to the close()
method:
// Assuming 'ws' is your WebSocket object
ws.close(code, reason);
Where code
is an optional numerical code indicating the reason for closure, and reason
is an optional human-readable explanation for why the connection is being closed.
Here’s an example of closing a WebSocket connection with a code and reason:
// Assuming 'ws' is your WebSocket object
ws.close(1000, "Closing connection gracefully.");
This code closes the WebSocket connection with a status code of 1000 (indicating a normal closure) and provides the reason “Closing connection gracefully.”
Remember that closing the WebSocket connection terminates communication between the client and server, so make sure to handle the closure appropriately based on your application’s requirements.