To use WebSockets in JavaScript, you'll primarily interact with the WebSocket API. Here's a concise overview:
1. Create a WebSocket Object
Instantiate a new WebSocket object, providing the URL of your WebSocket server. Use wss:// for secure connections, similar to https://.
let socket = new WebSocket("wss://your-websocket-server.com/path");
2. Handle Events
WebSockets are event-driven. You'll attach functions to these events:
-
onopen: Fired when the connection is successfully established.
socket.onopen = (event) => {
console.log("Connection established!");
};
-
onmessage: Fired when data is received from the server. The received data is in event.data.
socket.onmessage = (event) => {
console.log(`Data received: ${event.data}`);
};
-
onclose: Fired when the connection is closed. event.wasClean indicates if it was a clean closure, and event.code provides a status code.
socket.onclose = (event) => {
console.log(`Connection closed: ${event.code} ${event.reason}`);
};
-
onerror: Fired if an error occurs during connection or communication.
socket.onerror = (error) => {
console.error("WebSocket Error:", error);
};
3. Send Data
Use the send() method to transmit data to the server. Data can be a string or binary (ArrayBuffer or Blob).
socket.send("Hello from the client!");
4. Close the Connection
To close the WebSocket connection, call the close() method.
socket.close();
Remember that WebSockets enable real-time, two-way communication between a client and a server, making them ideal for applications requiring continuous data exchange like chat apps or online games.
-# Response generated by gemini-2.5-flash. AI may be incorrect or misleading.