How to import socket.io on client side - SOCKET.IO + NODE.JS

Viewed 8181

I have been trying to create an online game but when I try to use socket.on(...); or socket.emit(...) it comes up with an error like what is socket. I have seen some posts similar to this one and tried all the solutions but none worked. I have already got io.connect(...); working and it works (I assume this means I have properly set up socket.io-client). I just don't see what I am doing wrong. If you need the code you can simply request it though I don't think it was necessary. Thanks.

2 Answers

To use SocketIO on the client-side, first import it via

import * as io from 'socket.io-client';

Then, probably in a constructor, establish a connection to the server's ip and port running the SocketIO server

const socket = io(`172.16.1.3:81`);

Also in the constructor you will likely want to setup a function to be called when the server sends a certain message type:

socket.on("update-player", handlePlayerUpdateFunction);

and

function handlePlayerUpdateFunction(message) {
    console.log(`Received message from server: ${message}`);
}

If this client does not receive the message sent from your server, then something is wrong with your server not being set up correctly to listen on the port.

After trying some things and doing some research I found the solution to my problem. Adding in var socket = io.connect(x.x.x.x:3000); my code started functioning and everything was perfect I had already imported socket.io-client trough CDNJS link on the installation guide. I just had to Initialise the variable.

Related