I’m working on an Express server and need to use both socket.io and raw WebSocket (ws) simultaneously. My project is built around socket.io for real-time communication, but I need to integrate Twilio media streams, which only supports raw WebSocket.
Here is the basic setup I’m using:
import express from 'express';
import http from 'http';
import WebSocket from 'ws';
import { Server as SocketIOServer } from 'socket.io';
const app = express();
const server = http.createServer(app);
// Setup socket.io
const io = new SocketIOServer(server);
io.on('connection', (socket) => {
console.log('Socket.io client connected');
socket.on('message', (message) => {
console.log('Message from socket.io client:', message);
});
});
// Setup raw WebSocket
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
console.log('Raw WebSocket client connected');
ws.on('message', (message) => {
console.log('Message from raw WebSocket client:', message);
});
});
server.listen(5000, () => {
console.log('Server is listening on port 5000');
});
Context:
My project and client-side code are primarily built using socket.io, and I need to support real-time communication with Twilio media streams, which only work with raw WebSocket.
I am facing issues with connection conflicts and message handling between socket.io and raw WebSocket on the same server.
1