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

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.

Related

I have a two node js servers. second server is for the socket connection. How do I establish a connection between these two servers?

I'm setting up another nodejs server for the socketio, which is index.js. so I have two servers one is app.js and other one is index.js. so how do i establish a connection between these two servers?
If I correctly get what you wanted to do. You wanted to separate the file of the recieving of socket. Here's my code below.
on your app.js
var app = Express();
var server = require('http').createServer(app);
var io = SocketIo.listen(server);
server.listen(function(){
require('/path/of/your/index.js')(io);
})
and on your index.js
module.exports = function(io){
io.on('connection', function(socket){
*your codes here*
});
}
Can you please explain your problem in detail.And second thing, I don't understand why you want to establish two servers.Because you can always connect socket.io using your Node server.The code for it is below:
//Server side code
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
//Client Side code
var socket = io.connect();
socket.emit('my other event', {
data : 'Hello'
});
This is very basic example for client-server communication using socket.io
I hope you will get your answer.

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>

socket.IO can only connect one client (browser) at a time

I am having a problem of using socket IO to connect my server to the client(http website).
On the client, I have a button that when pressed, sends data to the server. However, this only works with one client.
If I have two clients, the first person to open the http website gets the socket IO connection, while the second person can open the page, but can't send any data to the server.
On the client side:
var socket = new io.connect('ServerIP:8090');
socket.on('message', function(obj){
if ('buffer' in obj){
//ignore this
} else message(obj);
});
On server side:
var io = io.listen(server)
, buffer = [];
io.on('connection', function(client)
{
client.send({ buffer: buffer });
client.broadcast.send({ announcement: client.sessionId + ' connected' });
chatGuests.push(client);
client.on('message', function(message){
var msg = { message: [client.sessionId, message] };
buffer.push(msg);
if (buffer.length > 15) buffer.shift();
client.broadcast.send(msg);
});
client.on('disconnect', function(){
client.broadcast.send({ announcement: client.sessionId + ' disconnected' });
});
Instead of using client.broadcast.send(something) and client.send(something) use io.emit('eventName', something). Also, for setting up the server with the variable io use
var socket = require('socket.io');
var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = socket.listen(server);
And then after your code:
server.listen(8090);
This allows you to use the node.js module express, which allows additional communication between the client and server (but doesn't require you to rewrite your socket.io code).
For your client code, instead of using:
socket.on('message', function(obj){
//Do something
});
Use:
socket.on('eventName', function(something){
//Do something
});
This works for multiple kinds of data passing, not just messages. You can multiple event listeners to each do different things

Socket.io will not work

I have changed my files to look as shown below. The javascript console shows nothing and the web page shows nothing. Just a blank screen. Does anybody know of a web site which uses socket.io. I would like to inspect the code to see how they do it since none of the examples on the socket.io page work for me. Does anybody know if extra ports need to be allowed in the iptables file?
Using the Chrome browser, if I goto the javascript console and goto the Network tab I get successes but the last call says Pending ??? It looks like it is hung. Could this be a firewall issue?
/socket.io/1/websocket
GET
101
Switching Protocols
Pending
Other
127 B
0 B
Pending
it is Pending in selector.js on line 168:
document.body.appendChild(menuDiv);
Maybe this is why I am not seeing anything? It is properly serving up socket.io/socket.io.js
Files below:
//app.js
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.use(express.static(__dirname + '/public'));
var port = 80;
var io = require('socket.io').listen(server, {
log : false
});
io.sockets.on('connection', function(socket) {
socket.on('hi', function(data) {
console.log('yay');
socket.emit('hello');
});
});
server.listen(port);
public/index.html
//index.html
<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
var chat = io.connect('http://localhost/chat')
, news = io.connect('http://localhost/news');
chat.on('connect', function () {
chat.emit('hi');
});
chat.on('hello',function(){
console.log('yay got hello');
});
var socket = io.connect('http://localhost:80');
socket.on('connect', function () {
chat.emit('hi');
});
socket.on('hello',function(){
console.log('yay got hello');
});
</script>
You're using namespaces news and chat even though your server doesn't implement them correctly.
You javascript connection should look like this instead:
var socket = io.connect('http://localhost:80');
socket.on('connect', function () {
chat.emit('hi');
});
socket.on('hello',function(){
console.log('yay got hello');
});

Socket.io Error (socket.send is not a function)

I'm trying out Websockets/Node.js/Socket.io/Express for the first time and I'm trying to create a simple chat program. Everything runs fine and I see both clients in my node termial.
But when I try to execute my socket.send(), I get an error in Firefox (socket.send is not a function). It doesn't complain about socket.connect() so I know the socket.io.js is loaded.
Here is my server code:
var sys = require('util');
var express = require('express');
var io = require('socket.io');
var app = express.createServer();
app.listen(8080);
app.use(express.static(__dirname));
app.get('/', function (req, res) {
res.render('index.html', {
title: 'Chat'
});
});
var socket = io.listen(app);
socket.on('connection', function (client) {
client.on('message', function (message) {
console.log("Message: " + JSON.stringify(data));
socket.broadcast(message);
});
client.on('disconnect', function () {});
});
My client code:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
var socket = new io.Socket("http://localhost:8080");
socket.connect();
Then I do some code to get the chat message and send it.
socket.send(JSON.stringify(values));
Explanations
You haven't initialized Socket.io correctly on the server-side and client-side.
Client Side
new io.Socket("http://localhost:8080"); doesn't give you the object that you want, you need new io.connect("http://localhost:8080");.
You need to wait until the client is connected to the server before sending a message.
Server side
socket is the object send back by Socket.IO, you need to use socket.sockets to have access to on.
To broadcast a message, you need to use the client object like this: client.broadcast.send()
The variable data doesn't exist on your broadcast. You probably mean message.
Solution
Server
var sys = require('util'),
express = require('express'),
io = require('socket.io'),
app = express.createServer();
app.listen(8080);
app.use(express.static(__dirname));
app.get('/', function (req, res) {
res.render('index.html', {
title: 'Chat'
});
});
var io = io.listen(app);
io.sockets.on('connection', function (client) {
client.on('message', function (message) {
console.log("Message: " + JSON.stringify(message));
client.broadcast.send(message);
});
client.on('disconnect', function () {});
});
Client
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
var socket = new io.connect("http://localhost:8080"),
connected = false;
socket.on('connect', function () {
connected = true;
});
// Use this in your chat function.
if (connected) {
socket.send(JSON.stringify(values));
}
</script>
socket.broadcast(message); should be io.sockets.emit('key', message);
when you use the socket object passed in threw the connect event your only emitting information to that client, to emit to all clients you have to use io.sockets.emit().
also with socket.send(JSON.stringify(values)); I think you want to do socket.emit(namespace, data);
see my connection file from one of my projects here: https://github.com/AdminSpot/HangoutCanopy/blob/master/javascripts/connection.js
You have to wait for socket.io to connect on the client side
var socket = new io.Socket("http://localhost:8080");
socket.connect();
socket.on('connect', function() {
socket.emit('event', data);
});

Resources