Here is a simple example of using Socket.IO with TypeScript:
Server-side (Node.js)
import * as express from 'express';
import * as http from 'http';
import * as socketIO from 'socket.io';
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('a user disconnected');
});
socket.on('chat message', (msg) => {
console.log(`received message: ${msg}`);
io.emit('chat message', msg);
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
Client-side (Browser)
import * as socketIO from 'socket.io-client';
const socket = socketIO();
socket.on('connect', () => {
console.log('connected to server');
});
socket.on('disconnect', () => {
console.log('disconnected from server');
});
socket.on('chat message', (msg) => {
console.log(`received message: ${msg}`);
document.getElementById('messages').innerHTML += `<p>${msg}</p>`;
});
document.getElementById('send-btn').addEventListener('click', () => {
const msg = document.getElementById('message-input').value;
socket.emit('chat message', msg);
document.getElementById('message-input').value = '';
});
HTML (index.html)
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Chat</title>
</head>
<body>
<h1>Socket.IO Chat</h1>
<input id="message-input" type="text" />
<button id="send-btn">Send</button>
<div id="messages"></div>
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io.js"></script>
<script src="client.js"></script>
</body>
</html>
This example sets up a simple chat application where users can send messages to each other in real-time using Socket.IO. The server-side code sets up an Express.js server and uses Socket.IO to handle incoming connections and emit events to connected clients. The client-side code uses the Socket.IO client library to connect to the server and handle incoming events.
Note that in the client-side code, we use the socketIO
function from the socket.io-client
library to create a new Socket.IO client instance. We then use the socket
object to emit events to the server and handle incoming events.
Also, make sure to install the required dependencies by running npm install express socket.io socket.io-client
in your project directory.