Home   web-development  

difference between WebSockets and WebRTC

WebSockets and WebRTC are both technologies used for real-time communication over the web, but they serve different purposes and have distinct characteristics. Here's a comparison between WebSockets and WebRTC:

WebSockets

Description: WebSockets provide a full-duplex communication channel over a single, long-lived connection between a client (typically a web browser) and a server. They are used primarily for bidirectional communication between the client and server.

Key Features:

Use Cases:

Example:

// Client-side (JavaScript)
const socket = new WebSocket('ws://example.com/socket');

socket.onopen = () => {
  console.log('WebSocket connection established');
  socket.send('Hello Server!');
};

socket.onmessage = (event) => {
  console.log('Message from server: ', event.data);
};

socket.onclose = () => {
  console.log('WebSocket connection closed');
};

socket.onerror = (error) => {
  console.error('WebSocket error: ', error);
};

WebRTC

Description: WebRTC (Web Real-Time Communication) is a set of protocols and APIs that enable peer-to-peer communication between browsers or devices. It supports audio, video, and data sharing.

Key Features:

Use Cases:

Example:

// Client-side (JavaScript)
const localConnection = new RTCPeerConnection();
const remoteConnection = new RTCPeerConnection();

// Creating a data channel
const dataChannel = localConnection.createDataChannel('chat');

// Handling data channel events
dataChannel.onopen = () => console.log('Data channel opened');
dataChannel.onmessage = (event) => console.log('Message from peer: ', event.data);

// Setting up ICE candidates
localConnection.onicecandidate = (event) => {
  if (event.candidate) {
    remoteConnection.addIceCandidate(event.candidate);
  }
};

remoteConnection.onicecandidate = (event) => {
  if (event.candidate) {
    localConnection.addIceCandidate(event.candidate);
  }
};

// Creating offer and answer
localConnection.createOffer().then((offer) => {
  return localConnection.setLocalDescription(offer);
}).then(() => {
  return remoteConnection.setRemoteDescription(localConnection.localDescription);
}).then(() => {
  return remoteConnection.createAnswer();
}).then((answer) => {
  return remoteConnection.setLocalDescription(answer);
}).then(() => {
  return localConnection.setRemoteDescription(remoteConnection.localDescription);
});

// Sending a message
dataChannel.onopen = () => {
  dataChannel.send('Hello Peer!');
};

Comparison Summary

Published on: Jul 08, 2024, 03:53 AM  
 

Comments

Add your comment