# Introduction to WebSockets

> Learn how WebSockets give you a long-lived, bidirectional channel between client and server, how they differ from HTTP, and how to open a connection with wss.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2018-04-28 | Updated: 2019-10-16 | Topics: [Networking](https://flaviocopes.com/tags/network/) | Canonical: https://flaviocopes.com/websockets/

WebSockets are an alternative to HTTP communication in Web Applications.

They offer a long lived, bidirectional communication channel between client and server.

Once established, the channel is kept open, offering a very fast connection with low latency and overhead.

## Browser support for WebSockets

WebSockets are supported by all modern browsers.

![Browser support for WebSockets](https://flaviocopes.com/images/websockets/browser-support.png)

## How WebSockets differ from HTTP

HTTP is a very different protocol, and also a different way of communicate.

HTTP is a request/response protocol: the server returns some data when the client requests it.

With WebSockets:

- the **server can send a message to the client** without the client explicitly requesting something
- the client and the server can **talk to each other simultaneously**
- **very little data overhead** needs to be exchanged to send messages. This means a **low latency communication**.

**WebSockets** are great for **real-time** and **long-lived** communications.

**HTTP** is great for **occasional data exchange** and interactions initiated by the client.

**HTTP is much simpler** to implement, while WebSockets require a bit more overhead.

If you're not sure whether you need WebSockets, server-sent events, or plain polling, I built a free [decision helper](https://flaviocopes.com/tools/websocket-sse-polling/) that compares the three for your use case.

## Secured WebSockets

Always use the secure, encrypted protocol for WebSockets, `wss://`.

`ws://` refers to the unsafe WebSockets version (the `http://` of WebSockets), and should be avoided for obvious reasons.

## Create a new WebSockets connection

```js
const url = 'wss://myserver.com/something'
const connection = new WebSocket(url)
```

`connection` is a [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) object.

When the connection is successfully established, the `open` event is fired.

Listen for it by assigning a callback function to the `onopen` property of the `connection` object:

```js
connection.onopen = () => {
  //...
}
```

If there's any error, the `onerror` function callback is fired:

```js
connection.onerror = (error) => {
  console.log(`WebSocket error: ${error}`)
}
```

## Sending data to the server using WebSockets

Once the connection is open, you can send data to the server.

You can do so conveniently inside the `onopen` callback function:

```js
connection.onopen = () => {
  connection.send('hey')
}
```

## Receiving data from the server using WebSockets

Listen with a callback function on `onmessage`, which is called when the `message` event is received:

```js
connection.onmessage = (e) => {
  console.log(e.data)
}
```

## Implement a server in Node.js

[ws](https://github.com/websockets/ws) is a popular WebSockets library for [Node.js](https://flaviocopes.com/nodejs/).

We'll use it to build a WebSockets server. It can also be used to implement a client, and use WebSockets to communicate between two backend services.

Install it using [npm](https://flaviocopes.com/npm/):

```bash
npm init
npm install ws
```

The code you need to write is very little:

```js
const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8080 })

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    console.log(`Received message => ${message}`)
  })
  ws.send('ho!')
})
```

This code creates a new server on port 8080 (the default port for WebSockets), and adds a callback function when a connection is established, sending `ho!` to the client, and logging the messages it receives.

## See a live example on Glitch

Here is a live example of a WebSockets server: <https://glitch.com/edit/#!/flavio-websockets-server-example>

Here is a WebSockets client that interacts with the server: <https://glitch.com/edit/#!/flavio-websockets-client-example>

## Debugging websockets

Chrome and Firefox have a handy way to visualize all the information that is sent through WebSockets. Their DevTools support is always improving. Firefox at the time of writing has the most useful and informative debugging tool.

In both, you look into the Network panel and choose WS to filter only WebSockets connections.

I took these screenshots of Firefox (Developer Edition) in action:

![Firefox headers](https://flaviocopes.com/images/websockets/Screen_Shot_2019-10-15_at_20.24.09.png)

![Firefox detail](https://flaviocopes.com/images/websockets/Screen_Shot_2019-10-15_at_20.24.15.png)

The Firefox DevTools can do much more than what I showed. In the example I used to test, I'm just sending a string, but you can inspect any data that's sent in a more organized fashion:

![Data in Firefox](https://flaviocopes.com/images/websockets/Screen_Shot_2019-10-16_at_09.45.47.png)

Check out [this post on Mozilla Hacks](https://hacks.mozilla.org/2019/10/firefoxs-new-websocket-inspector/) to know more about how to use this tool.

Here is a screenshot of Chrome, which hopefully will improve its WebSockets debugging tools soon:

![Chrome](https://flaviocopes.com/images/websockets/Screen_Shot_2019-10-15_at_20.25.01.png)
