# WebSockets on Render

The WebSocket protocol enables real-time, bi-directional data streaming between a client and server. It's commonly used for app features like text chat, financial dashboards, and AI voice assistants:

<img src="../assets/images/docs/websocket-diagram.svg" width="550" alt="Diagram showing WebSocket messages between a client and a server" />

*Render [web services](web-services) can accept inbound WebSocket connections from the public internet.* Additionally, service types besides [static sites](static-sites) can initiate _outbound_ WebSocket connections over both the public internet and your [private network](private-network).

## Web service setup

In your web service code, you usually extend your existing HTTP server framework with WebSocket support. For example, in Node.js it's common to use the `ws` module with the Express framework to enable WebSocket connections.

See basic examples for some popular frameworks below, and consult your framework's documentation for additional details.

**Express (Node.js)**

This example uses Express along with the `ws` module:

```js:app.js
const express = require('express')
const { createServer } = require('http')
const WebSocket = require('ws')

const app = express()
const server = createServer(app)
const port = process.env.PORT || 10000

// Serves WebSocket connections at /ws (any path is fine)
const wss = new WebSocket.Server({ server, path: '/ws' })

// HTTP routes
app.get('/', (req, res) => {
  res.send('Hello over HTTP!')
})

// WebSocket connections
wss.on('connection', (ws) => {
  console.log('WebSocket client connected')

  ws.on('message', (message) => {
    console.log('Received:', message.toString())
    ws.send(`Hello over WebSocket!`)
  })
})

server.listen(port, () => {
  console.log(`Server listening on port ${port}`)
})
```

**FastAPI (Python)**

This example uses FastAPI's built-in WebSocket support:

```python:main.py
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI()