Ask coding questions

← Back to all posts
Connect to NodeJS Server
mwilki7 (278)

How do you get a client to connect to a nodejs server running on repl?
I'm attempting to make something along the lines of a simple chat room with socket.io (copied an example chat room app online that I will repurpose for a drawing/text multiplayer game).
https://repl.it/@mwilki7/Telestrations-Server
https://repl.it/@mwilki7/Telestrations2 (Client)

Correct me if I'm misunderstanding this but,
I want the client to connect to the server (but I need to know the server's ip) so I do:

Server:
var ip = require("ip");
console.dir ( ip.address() );

server.listen(6969);

Log it so I can paste that IP in the client's connect function call:

Client
var socket = io.connect('172.18.0.78:6969');

But the client gets a timeout error and it seems that it can't connect to the server. I have verified that the server is running first.

Anyone know what I'm doing wrong?

Thanks!

Post-note!

This works with localhost in my Visual Studio project, any time I make a nodejs app for repl.it it just doesn't seem to work out.

Answered by JustARatherRidi (190) [earned 5 cycles]
View Answer
Commentshotnewtop
JustARatherRidi (190)

This might be the easiest fix you've ever seen, all you have to do is literally just replace line 16 in your client side html file with this

var socket = io();

And you're set.

So you don't need any of that ip address stuff, socket.io takes care of all that for you.

Here's a working repl


As a side note, you don't really need another repl for the client, simply running the server side code should do the job as you can see here in my very own shamelessly advertised app.

Also, is there any reason you use console.dir instead of console.log? I never got what the use of console.dir is.

mwilki7 (278)

@JustARatherRidi
Didn't seem to work. Console is logging connection timeout

console.dir is just something I got from https://stackoverflow.com/questions/3653065/get-local-ip-address-in-node-js

JustARatherRidi (190)

@mwilki7 But it does work, did you check my fork of your repl?

mwilki7 (278)

@JustARatherRidi
ohhhhh I had no idea you could put client and server in the same repl
That's supercool, thanks!

JustARatherRidi (190)

@mwilki7 No problem, glad I could help! :)

Also, I think you're a little too surprised for someone who already did put the server and client in the same repl :P

mwilki7 (278)

@JustARatherRidi what the heck I didn't even realize

JustARatherRidi (190)

@mwilki7 That's just how programming is sometimes lol

Cheers!