WebSocket Programming with JavaScript (Frontend)
WebSockets use a unique URL scheme to establish connections. A WebSocket URL begins with ws:// or wss://
for secure connections, similar to http:// and https://
in HTTP. The structure typically looks like this: ws://example.com/path
. Here, example.com
is the server address, and /path is the endpoint on the server handling WebSocket connections.
To use WebSocket URLs in your application, you should:
Use ws:// for unencrypted and wss://
for encrypted connections. The latter is similar to HTTPS and is crucial for security in production environments.To establish a WebSocket connection using plain JavaScript, you can use the WebSocket API provided by most modern browsers.
Here’s a basic example:
const socket = new WebSocket('ws://example.com/path'); socket.onopen = function(event) { console.log('Connection established'); }; socket.onerror = function(error) { console.error('WebSocket Error:', error); };
wss://
over ws://
to encrypt the data transfer.WebSockets provides various events that you can handle:
This event occurs when a connection is successfully established.
socket.onopen = function(event) { // Handle open event };
Triggered when data is received from the server.
socket.onmessage = function(event) { console.log('Message from server:', event.data); };
Occurs on any connection error.
socket.onerror = function(error) { // Handle error };
Triggered when the connection is closed.
socket.onclose = function(event) { console.log('Connection closed'); };
To send data to the server, use the send
method of the WebSocket object:
socket.send('Your message here');
For receiving data, the onmessage event
is used. This event is triggered whenever the server sends data to the client.
Here’s an example of how to handle incoming messages:
socket.onmessage = function(event) { console.log('Message from server:', event.data); // Process the received data based on your application's needs };
In this code snippet, event.data
contains the data sent by the server. You can process this data according to the needs of your application, such as updating the UI in real-time, parsing JSON data
, or handling binary data.