Attila
Attila

Reputation: 1177

Connecting front-end native websocket client to Node.js Socket.io server

I am using Socket.io in my Express/Node.js app for the backend websocket server. The server side code looks like this:

const socketIo = io(server);
socketIo.on('connection', (client) => {
    console.log('client connected');
    client.emit('test', { test: '123' });
    client.on('client-test', (data) => {
        console.log('from client: ', data);
    });
});

On the front-end (hosted on the same Node.js server), I am using native websockets, I have this:

const socket = new WebSocket('ws://localhost:3001');

socket.onopen = () => {
    socket.send('I am a client and I am listening');

socket.onmessage = (event) => {
    console.log('Client received message: ', event);
};

socket.onclose = (event) => {
    console.log('Client socket has closed: ', event);
    }
};

The websocket connection never seems to be established (I get nothing logged from the server). Furthermore, I'm not sure how to accepted the emitted message from the server on the client-side (i.e. the 'test' message) nor how to accepted the message on the server from the client (i.e. the server is expecting some 'client-test' message).

I'm wondering if native websockets on the front-end are incompatible with Socket.io on the backend. I had my set-up working when using Socket.io on the front-end as well, but I would like to have it working with native websockets on the front-end if possible.

Upvotes: 4

Views: 4020

Answers (1)

user2652134
user2652134

Reputation:

Socket.io is not native websockets, it has a custom transport layer. To communicate with socket.io you need https://github.com/socketio/engine.io-client.

Alternatively you can use native websocket libraries in the backend. Like : https://github.com/websockets/ws

Upvotes: 5

Related Questions