I can't setup socket in my page with Socket.io - node.js

How can I setup socket in client at my page with url
/localhost:3000/post/:id
In client I set
socket=io("http://localhost"3000/post/:id")
but when I listen in server with io.on("connection") , it isn't active.

In the client side you just need to include the socket.io cdn file and when you are on same host you don't have to include the full url.
code sample for client side :
let socket = io.connect();
socket.emit("connection",{});
For better understanding please view documentation as said on previous comment.

This is how you should configure it :
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('a user connected');
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
Read this documentation to understand it better https://socket.io/docs/v3

Related

Can't connect to Socket.io nodejs server

This is the code of the Server:
var http = require('http');
var app = require('express')();
http = http.createServer(app).listen(3400,() => {
var io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('connection');
});
});
I am using the Socket.io Client Test Tool: https://amritb.github.io/socketio-client-tool/
When I enter the address http://myWANIP:3400 as the URL and hit connect, nothing happens.
What am I doing wrong?
Any help is much appreciated :D
Edit: The Host is behind a NAT and the port 3400 is being forwarded (TCP).
Edit2: After some helpful comments I changed the code to:
var http = require('http');
var app = require('express')();
var server = http.createServer(app).listen(3400);
var io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('connection');
});
Your second code block looks more appropriate. We can't really tell if your NAT and port forwarding is set up correctly, but if it is, then you should be able to make a socket.io connection from a web page with this:
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io("http://myWANIP:3400", {transports: ["webSocket"]});
</script>
And, when that connection occurs, you should see the results of console.log('connection'); in the server logs.
Another way to verify that your NAT and port forwarding is working correctly is to add this to your server:
app.get("/", (req, res) => {
console.log("got web page request");
res.send("hello");
});
Then, when you got to http://myWANIP:3400, in the browser, you should get a log on your server and a response page back that says "hello".

How can I connect a socket to the server?

I'm trying to create a socket in a client.js file to communicate with my server. I followed the official documentation ( https://socket.io/docs/#Using-with-Express ) with no success. Basically when I initialize my socket like this:
var socket = io();
i expect a message from my server (e.g. 'A user has connected') but nothing appear, letting me suppose that the connection never happens.
This is a project made on Glitch. I tried to follow socket.io documentation, simple examples or other questions tips. I both tried the suggested script before instantiate the socket and the cdn one.
//server.js
//dependencies
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
//listening to the port
http.listen(process.env.PORT || 3000, () => {
console.log("Listening on port " + process.env.PORT);
});
io.on('connection', function(socket){
console.log('A user has connected.');
});
//chat.html
//this is called right before </body>
<script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js'></script>
<script src='/socket.io/socket.io.js'></script>
<script src='/public/client.js'></script>
//client.js
var socket = io();
client.js is loaded as expected (and the console throws no errors) but i can't see 'A user has connected' as i'd expect.
You can check full source code here https://glitch.com/edit/#!/farlokko-advanced-node
Thanks.
UPDATE:
The problem was a wrong initialization of the passport.socketio module, which interfered with sicket.io . The main problem probably was a wrong store(memoryStore instead of mongo-store) and a wrong key for the cookie (express.sid instead of connect.sid).
Finally socket initialization was ok and had to be io.connect("host here").
As specified on the doc, you have to configure the client to connect to your localhost, and then, on the connection, you'll have your message :
<script>
var socket = io.connect('http://localhost'); // <--- HERE MAN
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>

expressJS and socket.io listening to different ports and socket.io client connect

So I have a nodejs application which uses socket.io and expressjs
I use port '3000' for the express app and port '8080' for the socket app
Is it possible to use the same port for both these services?(express and socket.io)
When i want to connect to a socket from the client, I use the following code:
var socket = io('http://localhost:8080')
whats the right way of connecting to it( I see various ways in tutorials across the internet) and have no clue.
Is it possible to use the same port for both these services?(express and socket.io)
yes
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(8080); //or 3000
When i want to connect to a socket from the client, I use the following code:
At the front end :
include socket.io lib
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080'); //or 3000
</script>
EDIT :
without express
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(8080);
For more info socket.io
Yes, it is possible for both to use the same port. In fact, you should use the same port to make the client connect to your web socket when he sends a request. Socket.io docs has tutorial on how to connect with express.
Code from socket.io docs:
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
If you want to connect socket with express-generator generated template, you this:
stackoverflow post

Socket.io 1.0.6 client event

I am currently learning to use socket.io with node js but I'm having a hard time because I think something may have changed between versions. I have a litte demo using 1.0.4 in which I use something like this to send events from the client and receive them in the server:
SERVER
var socketio = require('socket.io');
var http = require('http');
var app = express();
var server = http.Server(app);
var io = socketio.listen(server);
var port = process.env.PORT || 8080;
server.listen(port, function(){
console.log("Express server listening on port " + port);
});
io.on('connection', function (socket) {
socket.emit('connected');
socket.on('myEvent', function(){
console.log('myEvent has been emitted');
});
});
CLIENT
$(document).ready(function(){
$('#button').click(function(){
emitEvent();
});
});
var socket = io.connect('http://localhost:8080/');
socket.on('connected', function () {
alert('server says I am connected');
});
function emitEvent(){
socket.emit('myEvent');
}
With both versions I can open the socket on the client and receive the 'connected' event sent later from the server than launches the alert function. The problem here is when I want to send any other event from the client. "socket.emit('myEvent');" in the emitEvent function seems to work fine for the 1.0.4 version but not for the 1.0.6 version. I have been looking for info about the changes and trying to understand the whole module but cannot get to the solution. Does anyone know what am I doing wrong? Obviously the way sending client events has changed. I would appreciate if someone could help me with this issue. Thanks in advance.
I didn't understand the problem actually. But here's the code for your functionality.
client:
var socket = io.connect();
$('#button').click(function(){
socket.emit('myEvent');
});
socket.on('connected', function(){
alert "you are connected";
});
server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(app);
var port = process.env.PORT || 8080;
app.listen(port);
io.on('connection', function(socket){
socket.on('myEvent', function(){
socket.emit('connected');
console.log('emmited succesfully');
});
});

var socket = io.connect('http://yourhostname/');?

I try socket.io again since v.1.0 released.
As the doc,
https://github.com/Automattic/socket.io
Server side:
var server = require('http').Server();
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('event', function(data){});
socket.on('disconnect', function(){});
});
server.listen(5000);
Client side
var socket = io.connect('http://yourhostname.com/');
In development, surely
var socket = io.connect('http://localhost:5000/');
It works, but I'm very uncomfortable with hardcoding the hostname(subdomain.domain) in the client code(/index.js).
The index.js is hosted by the http-sever and the socket.io is bundled to the http-server in this configuration.
Is there any smart way not to hardcode the hostname but to code in some relative path?
Thanks.
EDIT:
When I try:
var socket = io.connect('./');
The connection error:
GET http://.:5000/socket.io/?EIO=2&transport=polling&t=1401659441615-0 net::ERR_NAME_NOT_RESOLVED
is like this, so at least the port number (5000) is obtained properly without hardcoding in the client side.
Final answer.
I have totally forgotton that we can obtain the current url/domain in browser.
window.location.hostname
So, simply goes:
'use strict';
/*global window, require, console, __dirname, $,alert*/
var log = function(msg)
{
console.log(msg);
};
log('init');
$('document').ready(function()
{
var io = require('socket.io-client');
var socket = io.connect(window.location.hostname);
socket.on('connect', function()
{
log('socket connected');
});
});
You have to remember that Node.js is not a web server. It's a platform. When you specify a relative path, it doesn't know that you mean "relative to the current domain."
What you need to do is send the domain to the client when you send them the webpage (I don't know the specifics of your setup, but perhaps using a template variable?), and send them the localhost:5000 domain if you're in development, or your real domain if you're in production (alternatively, you can use a library like nconf, but you get the idea).
dunno, so far I did as follows:
'use strict';
/*global window, require, console, __dirname, $,alert*/
var log = function(msg)
{
console.log(msg);
};
log('init');
$.getJSON("../config.json", function(data)
{
var host = data.url;
var port = data.port;
$('document').ready(function()
{
alert(host + ':' + port);
var io = require('socket.io-client');
var socket = io.connect(host);
socket.on('connect', function()
{
log('socket connected');
});
});
});
It's browserified with socket.io-client.

Resources