Lesson 53 of 56 · Typescript
WebSockets Typed with `ws`
Duration: 20 minutes
Install ws
npm i ws
npm i -D @types/ws
Server
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8081 });
wss.on('connection', ws => {
ws.on('message', (msg: string) => {
console.log('←', msg);
ws.send(`echo: ${msg}`);
});
});
Client (browser)
const socket = new WebSocket('ws://localhost:8081');
socket.addEventListener('open', () => socket.send('hello'));
socket.addEventListener('message', e => console.log('→', e.data));
Typed messages
type ChatMessage = { type: 'chat'; payload: string };
socket.send(JSON.stringify({ type: 'chat', payload: 'Hi' } as ChatMessage));