I am trying to connect two node.js servers using socket.io and socket.io-client. In both cases, I am using v0.9.16.
In my case, I call the servers the STREAM SERVER and the ACTIVITY SERVER where the activity server uses the socket.io-client module.
STREAM SERVER - (THE CODE ON THE SERVER THAT ACTS LIKE A SERVER)
var https = require('https');
var express = require('express');
var socket = require('socket.io');
var securePort = (process.env.LOCAL_HTTPS_PORT || 443);
var sslOptions = //CERTIFICATE
var socketIoConfiguration = //CONFIG VALUES
var app = express();
var server = https.createServer(sslOptions, app);
var io = socket.listen(server, socketIoConfiguration('activityToStream'));
io.sockets.on('connection', function (socket) {
console.log('Activity server connected to stream server.');
});
server.listen(securePort);
ACTIVITY SERVER - (THE CODE ON THE SERVER THAT ACTS LIKE THE CLIENT)
var socketClientModule = require('socket.io-client');
var streamConnectionServer = 'https://165.225.144.273:443';
var activityToStreamSocket = socketClientModule.connect(streamConnectionServer);
activityToStreamSocket.on('connect', function(socket){
console.log('Connected to Stream Server');
});
When I run this code, I don't get any message from either server. However, when I run this code from an HTML page served in Chrome, I see messages on the output of the Stream server:
<!DOCTYPE html>
<html>
<head>
<title>
Test
</title>
<script src="https://165.225.144.273/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('https://165.225.144.273');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</head>
<body>
Hello World
</body>
</html>
STREAM SERVER MESSAGES WHEN CLIENT RUN IN CHROME
debug: client authorized
info: handshake authorized UaUDRsA3ZBTgdsiLDCrl
debug: setting request GET /socket.io/1/websocket/UaUDRsA3ZBTgdsiLDCrl
debug: set heartbeat interval for client UaUDRsA3ZBTgdsiLDCrl
debug: client authorized for
debug: websocket writing 1::
So, it makes me think the issue is with my "ACTIVITY SERVER" running socket.io-client, but I cannot figure out why its not working at all (no error messages, etc.)
Use the same version of socket server and client
I had the same issue, but my solution was simple:
My code was wrong here:
var serverSocket = ioclient.connect('127.0.0.1:6000');
Then I wrote 'ws://' before '127.0.0.1', and it began to work.
var serverSocket = ioclient.connect('ws://127.0.0.1:6000');
That gave me a headache for hours.
I was able to get it to work using the following:
1) socket.io v 1.0.0-pre using this command
npm install git+https://github.com/LearnBoost/socket.io.git
2) scoket.io-client v 1.0.0-pre using this command
npm install git+https://github.com/LearnBoost/socket.io-client.git
3) I used an SSL certificate from a CA instead of self signed and then I used a DNS name instead of an IP address (see this on not using unsigned certificates with Socket.io)
Here's my server and client (server acting as client). Reference the Socket.io-client GitHub page.
SERVER CODE
var sslOptions = //CERTIFICATE
var app = require('express')(); // Express 3.x
var server = require('https').Server(sslOptions, app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
console.log('Connection from Activity Server');
for (var i=0; i<100000; i++) {
io.emit('event', i);
}
});
server.listen(443);
CLIENT CODE (SERVER ACTING AS CLIENT)
var now = Date.now();
var socket = require('socket.io-client')('https://example.com:443');
socket.on('connect', function(){
console.log('Connected to Stream Server');
socket.on('event', function(data){
console.log('Ping ' + data);
console.log(now + ' ' + Date.now());
});
});
Using this Socket.io code, I was able to get over 13,000 messages per second. This was done on two Joyent servers in the same data center (Memory 256 MB, CPUs 0.125 and bursting, Network Up to 10 Gbit/s).
When doing more of a "Ping Pong" style messaging, I was able to get about 650 messages per second.
Note the performance numbers are just a datapoint for reference, I didn't do any tweaking, heaving loading, etc.
I got the same situation but I fix this by switching the socketio-client version. I got socketio version 2.3. but I got socketio-client version 3.1. I changed the version of socketio client by using "npm install socket.io-client#2.3". in my client js file I use socket.io-client like that
const io = require('socket.io-client');
const socket = io('ws://localhost:3000',{
});
Related
This function doesn't work in my app. I can't receive a message (socket.emit) from the server to the client (socket.on).
But i don't have this problem in the inverse (client to server).
I use cloud9 and the chat example from them works fine.
Here is my code for the server :
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);
router.use(express.static(path.resolve(__dirname, 'client2')));
io.on('connection', function (socket) {
socket.emit('hello', 'i changed'); // !!!
});
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
and the code for the html page :
<html>
<head>
<title>test</title>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('hello', function (msg) { // !!!
document.innerHTML = msg;
});
</script>
</head>
<body>
<p>normal page</p>
</body>
</html>
And there is no change...
edit : with console.log either.
But the message seems sent with the socket :
Debugger listening on port 15454
info - socket.io started
Chat server listening at 0.0.0.0:8080
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized 13XpSYGuXzMpMeyFsRfO
debug - setting request GET /socket.io/1/websocket/13XpSYGuXzMpMeyFsRfO
debug - set heartbeat interval for client 13XpSYGuXzMpMeyFsRfO
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"hello","args":["i changed"]}
Can you help me please ?
You need to change
var socket = io.connect();
by
var socket = io.connect('http://0.0.0.0:8080');
var socket = io.connect() <- this should specify the domain to which you are connecting.
So i did alot in this, trying to get it to work, it sorta did but i don't work like you do, i'm a beginner and not compatible with how you code but i've figured out that the problem is the port the io is using
var io = socketio.listen(server);
or where the html is getting the connection
<script src="/socket.io/socket.io.js"></script>
to me, the html is requesting a js file in it's own dir, but it shouldn't.
When i use socket.io, i put this in the server
var client = require("socket.io").listen(8080).sockets
The main part is the listen, it listens on the port 8080 and in my html i do
var socket = io.connect("http://127.0.0.1:8080");
Which works, i'm sorry for this, i am mostly sure this isn't an answer but i've tried, i hope you get it done, even if a year and 3 months have passed.
$(function(){
var socket = io();
socket.on('hello',function(data){
$('#lblmsg').text(data.message);
});
});
this is something I am working with. in the 4th line of my code, data is passed and data.message is retrieved. but you directly equated msg with the innerhtml, on the html page(in the block you commented \!!!)
see if you are still working on it!
I am attempting to get some real time notifications into my Laravel 5 app. Building locally on a vagrant box with Homestead.
I can not work out what the issue is with the following set up.
My server.js is as follows ...
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(3000);
io.on('connection', function (socket) {
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, message) {
socket.emit(channel, message);
});
socket.on('disconnect', function() {
redisClient.quit();
});
});
Then my client code is to subscribe:
<script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3000');
socket.on('message', function (data) {
alert(data);
});
</script>
Firebug keeps returning:
GET http://127.0.0.1/socket.io/?EIO=3&transport=polling&t=1430825965165-1
Aborted
Chrome tools shows me the following:
http://127.0.0.1:3000/socket.io/?EIO=3&transport=polling&t=1430826106108-3 net::ERR_CONNECTION_REFUSED
Pretty new to NodeJs and very confused. Spent a good 4 hours now trying to work it out.
Any pointers?
many thanks, Dean.
First make sure that you have installed all dependencies of your server.js file, if you are working with Homestead, execute the following command in your root project directory:
npm install express redis socket.io --save
Wait until installation finish and start the server with:
node server.js
Use your project's virtual host name for connect with socket.
It works for me.
Edit this in your client code.
var socket = io.connect('http://' + location.host + ':3000');
I want to use the tcp net module in node.js, my clients will be browser and also not browser ( device ).
when I tried to run in the browser the index.html, my browser keeps loading looks like it looping..I dont know what's wrong in my code.
I tried use telnet it works fine, the problem is on the browser i cannot load properly the index.html
//app.js
var net = require('net');
var io = require('socket.io')(net);
var clients = [];
var server = net.createServer(function (socket) {
console.log("New client connected");
clients.push(socket);
});
server.listen(1337, 'localhost', false, function () {
console.log('server bound');
});
io.on('connection',function(socket){
socket.emit('news', { hello: 'world' });
});
here is my client code.
http://pastie.org/10115599
Both the browser and socket.io require an http server, not just a TCP server. You can see the code examples in the socket.io documentation. The first server and client code example on that doc page shows you the basics you need.
In fact, the first step in socket.io connection is an http request that is then "upgraded" to the webSocket protocol. So, the server must be an http server. And socket.io hooks into an http server in order to receive incoming connections.
Here's a code example from the socket.io doc:
Server Code:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
app.listen(80);
io.on('connection', function (socket) {
// incoming socket.io connection established
});
function handler (req, res) {
// process http requests for normal web page serving
}
Client Code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
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.
iam trying to connect php application with another nodejs application on heroku using socket.io
code using for connection on client (php app)
<script src="http://mynodeapp.herokuapp.com/socket.io/socket.io.js/"></script>
<script language="javascript" type="text/javascript">
var reguser_socket = io.connect('http://mynodeapp.herokuapp.com');
console.log("connected");
<script>
code using on server (nodejs app)
var http = require('http');
var port = process.env.PORT || 4000;
var app = http.createServer(handler).listen(port);
var io = require('socket.io').listen(app);
io.configure(function(){
io.set('log level', 1);
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
io.sockets.on('connection', function (socket) {
console.log("client has connection established ");
});
But while runnig this i get
GET http://mynodeapp.herokuapp.com/socket.io/1/?t=1384779309815
(Internal Server Error)
In order to use Web Sockets on Heroku, you need to run:
heroku labs:enable websockets
because it is only in public beta.
See here for a general overview on how to use it with Heroku:
https://devcenter.heroku.com/articles/node-websockets
This section of code works fine my connection was interrupted because i have another part of code cause this problem