Web Socket Example: Real-World Code, Architecture & Multi-Language Guide (2025)

A practical guide to web socket examples in JavaScript, Node.js, Go, Arduino/ESP32, and PHP. Covers architecture, code, real-world uses, and security in 2025.

Web Socket Example: Practical Guide with Real-World Code

Introduction to Web Socket Example

Web sockets have revolutionized real-time web communication by enabling persistent, bidirectional connections between clients and servers. This post demystifies the concept with hands-on web socket examples in JavaScript, Node.js, Go, Arduino/ESP32, and PHP, addressing both client and server implementations. Whether you are building chat applications, IoT dashboards, or collaborative platforms, mastering web sockets is essential in 2025. We'll explore architecture, showcase code snippets, and provide best practices for security, so you can implement robust real-time features in your projects.

What is a Web Socket?

A web socket is a protocol providing full-duplex communication channels over a single, long-lived TCP connection. Defined by

RFC 6455

, web sockets enable low-latency, real-time data exchange between browser clients and servers, unlike traditional HTTP which is request-response based and stateless.
Key Differences: WebSockets vs HTTP:
  • Persistence: WebSockets establish a connection that remains open, while HTTP closes after each request/response.
  • Duplex Communication: WebSockets allow both server and client to send messages independently. HTTP only allows the server to respond to client requests.
  • Low Overhead: WebSockets reduce protocol overhead after the initial handshake.
Use Cases:
  • Real-time chat and collaboration apps
  • Live dashboards and financial tickers
  • Multiplayer gaming
  • IoT device monitoring and control
  • Live notifications and streaming
Web sockets are a foundational technology for real-time web apps and IoT systems in 2025, providing the low-latency, scalable communication modern users expect. For developers looking to implement scalable, interactive live streaming features, integrating a

Live Streaming API SDK

can further enhance your application's real-time capabilities by leveraging robust APIs designed for high-quality, low-latency streaming experiences. If your project requires real-time audio communication, exploring a

phone call api

can help you seamlessly add voice calling features to your applications. For a streamlined approach to integrating video calling functionality, you can

embed video calling sdk

directly into your web application, enabling robust video and audio communication with minimal setup. Additionally, if you're building real-time communication features in Python, leveraging a

python video and audio calling sdk

can help you quickly integrate high-quality video and audio call capabilities into your Python applications. If you're developing cross-platform mobile apps with React Native, integrating a

react native video and audio calling sdk

provides a seamless way to add real-time video and audio communication to your mobile projects.

How Web Sockets Work: Architecture & Flow

Web sockets start with an HTTP handshake, upgrading the protocol to WebSocket, which then keeps the connection open for continuous communication. This persistent connection allows both parties to send and receive data at any time, making web sockets perfect for real-time, interactive applications.

Connection Lifecycle

  1. Handshake: The client sends a WebSocket handshake request over HTTP(S). The server responds, upgrading the connection if supported.
  2. Open Connection: After a successful handshake, the connection becomes persistent (TCP-based).
  3. Data Exchange: Both client and server can send data asynchronously.
  4. Close Connection: Either side can close the connection when done.

When to Use Web Sockets

  • You need instant updates (chats, dashboards)
  • Continuous two-way data exchange is required
  • Reducing latency and server overhead is critical

WebSocket Connection Lifecycle Diagram

Web Socket Example in JavaScript (Client Side)

JavaScript provides native WebSocket support in modern browsers, making client-side implementation straightforward. Below is a basic example demonstrating how to connect to a WebSocket server, send a message, and handle responses.
For developers building advanced real-time communication features, such as live video and audio calls, integrating a

javascript video and audio calling sdk

can further streamline the process and provide robust APIs for seamless user experiences. If you're working with React, leveraging a

react video and audio calling sdk

offers an efficient way to add high-quality video and audio call capabilities to your real-time web applications. Additionally, if you're developing cross-platform mobile apps, exploring

flutter webrtc

can help you implement real-time video and audio communication using WebRTC in Flutter projects. For Android developers, integrating

webrtc android

enables seamless real-time video and audio communication within native Android apps, expanding your real-time capabilities across platforms. For a more comprehensive solution, consider using a

Video Calling API

to quickly integrate high-quality video and audio communication into your applications with minimal effort.
1const ws = new WebSocket("wss://example.com/socket");
2
3// Connection opened
4ws.addEventListener("open", (event) => {
5  console.log("Connected to WebSocket server.");
6  ws.send("Hello Server!");
7});
8
9// Listen for messages
10ws.addEventListener("message", (event) => {
11  console.log("Message from server ", event.data);
12});
13
14// Send a message
15function sendMessage(msg) {
16  if (ws.readyState === WebSocket.OPEN) {
17    ws.send(msg);
18  }
19}
20

Handling Events and Errors

WebSocket objects emit several events: open, message, error, and close. Always handle these events to monitor connection status and errors.
1ws.addEventListener("error", (event) => {
2  console.error("WebSocket error:", event);
3});
4
5ws.addEventListener("close", (event) => {
6  console.log("WebSocket connection closed.");
7});
8

Web Socket Example in Node.js

Node.js, with its event-driven architecture, is ideal for building WebSocket servers. The ws library is a popular choice for implementation.
Install the ws library: bash npm install ws
Sample Echo Server: ```javascript const WebSocket = require("ws"); const wss = new WebSocket.Server({ port: 8080 });
wss.on("connection", (ws) => { ws.on("message", (message) => { console.log("received: %s", message); ws.send("Echo: " + message); }); ws.send("Welcome to the WebSocket server!"); }); ```
This example sets up a simple echo server that responds to each message from the client.

Web Socket Example in Go (Golang)

Go's concurrency model is well-suited for WebSocket servers. The

gorilla/websocket

package offers a robust implementation.
Install gorilla/websocket: bash go get github.com/gorilla/websocket
Sample Echo Server: ```go package main
import ( "log" "net/http" "github.com/gorilla/websocket" )
var upgrader = websocket.Upgrader{}
func echo(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Print("upgrade:", err) return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) break } log.Printf("recv: %s", message) err = c.WriteMessage(mt, message) if err != nil { log.Println("write:", err) break } } }
func main() { http.HandleFunc("/ws", echo) log.Fatal(http.ListenAndServe(":8080", nil)) } ```

Web Socket Example with Arduino/ESP32

Web sockets enable real-time communication between IoT hardware and web clients. The ESP32, with its WiFi capabilities, is a popular choice for these applications. We'll use the ESPAsyncWebServer and WebSocketsServer libraries for this example.
Install Libraries (in Arduino IDE Library Manager):
  • ESPAsyncWebServer
  • ESPAsyncTCP
  • WebSocketsServer
Example: Control an LED via WebSocket ```cpp

include <WiFi.h>

include <ESPAsyncWebServer.h>

include <WebSocketsServer.h>

const char ssid = "YOUR_SSID"; const char password = "YOUR_PASSWORD";
AsyncWebServer server(80); WebSocketsServer webSocket = WebSocketsServer(81); const int ledPin = 2; // Built-in LED
void handleWebSocketMessage(void arg, uint8_t *data, size_t len) { String msg = String((char)data); if (msg "ON") { digitalWrite(ledPin, HIGH); } else if (msg "OFF") { digitalWrite(ledPin, LOW); } }
void onWebSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) { if (type == WStype_TEXT) { handleWebSocketMessage(num, payload, length); } }
void setup() { pinMode(ledPin, OUTPUT); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); } webSocket.begin(); webSocket.onEvent(onWebSocketEvent); server.begin(); }
void loop() { webSocket.loop(); } ```
This sketch lets you toggle an LED from any WebSocket client connected to your ESP32.

Web Socket Example in PHP

PHP can serve as a simple WebSocket server using libraries like

Ratchet

or basic implementations for learning. Below is a minimal example using PHP's socket extension.
Simple PHP WebSocket Server: ```php <?php // Minimal WebSocket server (for learning/demo purposes) $host = '0.0.0.0'; $port = 8080; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_bind($socket, $host, $port); socket_listen($socket);
while (true) { $client = socket_accept($socket); $data = socket_read($client, 1024); // Simple handshake and echo logic omitted for brevity socket_write($client, "Echo: " . $data); socket_close($client); } socket_close($socket); ?> ```
For production, always use a robust library to handle WebSocket handshakes and protocol compliance.

Security Considerations for Web Sockets

Web sockets open persistent connections, which introduces unique security challenges:
  • Data Interception: Always use wss:// (WebSocket Secure) to encrypt traffic.
  • Cross-Origin Attacks: Validate the Origin header to restrict connections to trusted domains.
  • Authentication: Authenticate users before upgrading to a WebSocket connection.
  • Message Validation: Sanitize and validate all incoming messages to prevent injection attacks.
  • Resource Limits: Limit concurrent connections and message sizes to prevent denial-of-service (DoS) attacks.
Follow these best practices to ensure secure, robust WebSocket implementations in 2025.

Conclusion

Web sockets bring powerful, low-latency, real-time communication to modern web and IoT applications. With practical web socket examples in JavaScript, Node.js, Go, Arduino/ESP32, and PHP, you can rapidly prototype and scale real-time features for any project. Experiment with the code snippets above, and leverage the flexibility and speed of web sockets to build the next generation of interactive, connected solutions.

Get 10,000 Free Minutes Every Months

No credit card required to start.

Want to level-up your learning? Subscribe now

Subscribe to our newsletter for more tech based insights

FAQ