# Socket

> The Socket is an endpoint of a two-way network connection between two programs, defined by an IP address and a port.

## What is a socket in networking?

The endpoint of a network connection identified by an IP address and a port, through which a program sends and receives data. TCP sockets give a reliable ordered stream, UDP sockets send fast independent packets. WebSocket is a different thing: a protocol on top of a TCP connection.

- Topic: Network
- Type: concept

## Example

Wrong:

```js
socket.on('data', (chunk) => {
  const msg = JSON.parse(chunk);
  handle(msg);
});
```

Right:

```js
let buffer = '';
socket.setEncoding('utf8');
socket.on('data', (chunk) => {
  buffer += chunk;
  let i;
  while ((i = buffer.indexOf('\n')) !== -1) {
    handle(JSON.parse(buffer.slice(0, i)));
    buffer = buffer.slice(i + 1);
  }
});
```

TCP is a byte stream, so one `data` event may hold part of a message or several; framing with newlines splits them correctly.

## Common mistakes

- Confusing a raw TCP socket with the WebSocket protocol used in browsers.

## Key points

- The code closes the socket or connection when it is no longer needed.
- Server code handles connection errors and timeouts instead of assuming the socket stays open.

## Interview questions

### What is the difference between a socket and a port?

A port is a number on a machine. A socket is one endpoint of a connection, combining an IP address, a port and a protocol.

### Can a web page open a raw TCP socket?

No. Regular web pages can use only higher-level protocols such as HTTP, WebSocket, WebTransport and WebRTC.

### Why does one TCP read return half a message?

TCP delivers a stream of bytes, not messages. The app must add framing, such as a length prefix or a delimiter, to know where a message ends.

## Related cards

- [TCP](https://wonderium.dev/web/tcp.md)
- [UDP](https://wonderium.dev/web/udp.md)
- [WebSocket](https://wonderium.dev/web/websocket.md)
- [Port](https://wonderium.dev/engineering/port.md)
- [IP Address](https://wonderium.dev/web/ip-address.md)

---

- Level: [Web Platform](https://wonderium.dev/web.md)
- HTML version: https://wonderium.dev/web/network-socket
- Last updated: 2026-11-25
