I am trying to emit message from client side with socket.io ...
Here is my client code:
var socket = io.connect('http://localhost/');
socket.on('connect', function(data){
setStatus('connected');
socket.emit('subscribe', {channel:'update.comment'});
});
Server:
io.sockets.on('connection', function (socket) {
socket.emit('message', { text : 'Welcome!' });
socket.on('subscribe', function (data) {
socket.join(data.channel);
redisClient.subscribe(data.channel);
});
});
Also I get this error message in console:
GET
http://localhost/socket.io?EIO=3&transport=polling&t=1442169984269-1
404 (Not Found)
Full serever:
var app = require('express')();
var http = require('http').Server(app);
var redis = require('ioredis');
var io = require('socket.io')(http);
redisClient = redis.createClient();
//look for connection errors and log
redisClient.on("error", function (err) {
console.log("error event - " + redisClient.host + ":" + redisClient.port + " - " + err);
});
io.sockets.on('connection', function (socket) {
socket.emit('message', { text : 'Welcome!' });
//on subscription request joins specified room
//later messages are broadcasted on the rooms
socket.on('subscribe', function (data) {
socket.join(data.channel);
redisClient.subscribe(data.channel);
});
});
redisClient.on('ready', function(data) {
console.log('#redis ready');
});
redisClient.on("message", function(channel, message){
console.log(channel);
var resp = {'text': message, 'channel':channel};
io.sockets.in(channel).emit('message', resp);
});
http.listen(3000, function(){
console.log('Listening on Port 3000');
});
New Problem Recognized:
Your server is listening on port 3000, but you are attempting to connect on port 80. The error message http://localhost/socket.io?EIO=3&transport=polling&t=1442169984269-1 has no port number on it so that defaults to port 80.
That error message means that your server-side socket.io code is not initialized correctly and thus is not listening for the HTTP request that starts all webSocket connections so when the browser tries to connect on that URL to initiate a socket.io connection, there's nobody on the server-side listening so the web server returns a 404 error back to the browser.
If you are using Express, this is the minimal socket.io initialization to hook it into your server:
var express = require('express');
var app = express();
var server = app.listen(8081);
var io = require('socket.io').listen(server);
For a plain HTTP server, this is the minimal socket.io initialization:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
app.listen(80);
As always, if you show us the socket.io and web server initialization code you are using, we can help you better with your specific code issue.
Related
I am on Node.js v4.1.1 and working with socket.io
when client connected to server socket and start exchanging packages at that time first packet missed on server.
have you guys any idea what is the reason behind this? Please note that we have around 900 connection at a time.
var http = module.exports = require('http');
var app = module.exports = express();
var httpsOptions = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('certificate.crt')
};
var Server = https.createServer(httpsOptions, app);
var io = module.exports = require('socket.io').listen(Server);
io.set("transports", ["xhr-polling", "web socket", "polling", "htmlfile"]);
io.sockets.on("connection", function(socket)
{
client.on('msg', function(request)
{
console.log("event get --> " + request);
});
client.on('error', function(exc)
{
console.log("ignoring exception: " + exc);
});
client.on('ping', function(request)
{
client.emit('pong', request);
client.removeListener('ping', function() {});
});
client.on('disconnect', function(reason)
{
console.log("socket disconnect " + reason);
});
});
In this case actually error not in socket or node.js. Error in mongodb , mongodb take so much load so all event's are late. Also new connection take load in sign up process.we just increase the configuration of mongodb and all working well.
When users do a GET /check/health, this client should talk to Server and sever should give the client the answer..
But the message from the server is not received on the client..
Client side - also acting as a webserver
var io = require('socket.io-client');
var socket = io.connect('http://localhost:4000', {reconnect: true});
var express = require('express');
var app= express();
var path = require('path');
var bodyParser= require('body-parser');
app.use(express.static(__dirname+"/public/"));
app.use(bodyParser.json());
app.set('views',path.join(__dirname,'/public/html'));
app.engine('html', require('ejs').renderFile); //specify which template engine to use
app.set('view engine', 'ejs');
app.get('/check/health',function(req,res){
//console.log('Connected Success!!');
socket.on('connect', function(socket) {
console.log('Connected!');
});
socket.emit('data', 'I need your health status');
socket.on('data', function(data) {
console.log('Message from monitoring is : ' + ': ' + data);
});
socket.on('server data', function(data) {
console.log('Received server data: ' + data);
});
});
app.listen(3000);
console.log("Server running at http://localhost:3000/'");
Server side:
var app = require('express')();
var SERVER = require('http').Server(app);
var io = require('socket.io')(SERVER);
var express = require('express');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sensor_db');
io.on('connection', function(socket){
console.log('connection received from Provisioning ');
// To get messages from Provisioning server
socket.on('data', function(data) {
console.log('Message from provision is : ' + ': ' + data);
});
socket.emit('server data', 'Here is yiour data - 1111');
});
SERVER.listen(4000, function(){
console.log('listening on *:4000');
});
There are a number of potential issues here, but the main one is that your server side code is missing the following very important line:
http.listen(4000);
Adding that should get you started down the right path. Also, I would suggest renaming the http variable to something else, since it's not the http module. server makes more sense to me.
Here's a more minimal example of what you're looking to do. It's missing a few things such as error handling, considering what should happen when a request to /check/health comes in and your socket.io connection isn't up, etc, but I'll leave that as an exercise for you. I also trimmed out some stuff that wasn't relevant to the question (mongoose, ejs templating, etc), so you'll have to add those back in when you're confident that this piece is working as intended.
Client Side
var io = require('socket.io-client');
var socket = io.connect('http://localhost:4000', { reconnect: true });
var express = require('express');
var app= express();
var path = require('path');
// careful here -- the socket.io connection will be made
// outside of the context of the /check/health callback,
// so you should move the connect event handler out here.
socket.on('connect', function(socket) {
console.log('Connected!');
});
app.get('/check/health',function(req,res){
// note the third argument here,
// which can be used as an acknowledgement from the server
// that your client's emit was received
socket.emit('data', 'I need your health status', function ack(data) {
console.log('data emit was acknowledged:', data);
// make sure you send something back to the requester
// or they'll just hang until timeout
return res.json(data);
});
// if you want, you could technically use socket.once('server data'),
// in this location, but this is probably going to be closer
// to the style of communication you actually want --
// which is one response to this specific single socket emit.
});
app.listen(3000);
console.log('Server listening at port 3000');
Server Side
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var express = require('express');
io.on('connection', function(socket){
console.log('connection received from Provisioning');
// To get messages from Provisioning server
socket.on('data', function(data, ack) {
console.log('Message from provision is : ' + ': ' + data);
ack('here is your data - 1111');
});
});
server.listen(4000, function(){
console.log('socket.io server listening on *:4000');
});
the client error is :
GET http://localhost:8888/socket.io/1/?t=1342788870007 404 (Not Found)socket.io.js:1632
Socket.handshake socket.io.js:1632
Socket.connect socket.io.js:1671
Socket socket.io.js:1530
io.connect socket.io.js:91
(anonymous function)
my client js:
var socket = new io.connect("http://localhost", 8888);
socket.on("chatRoom", function(data){
$("#log").html($("#log").html() + "<br>" + data);
})
$("#chatform").submit(function (event) {
event.preventDefault();
socket.emit('chatRoom', $("#chat").val())
})
and my server is:
var express = require('../node_modules/express'),
app = express.createServer(),
io = require('../node_modules/socket.io').listen(app),
fs = require('fs');
app.use(express.bodyParser());
var port = 8888;
// get html page ok
app.get('/html/*', function (req, res) {
res.sendfile(__dirname + '/html/' + req.params[0]);
});
// chat
io.sockets.on('connection', function (socket) {
socket.on("login", function(message){
socket.emit('chatRoom', "sombody connect");
})
socket.on("chatRoom", function(data){
socket.emit('chatRoom',"from server");
})
})
app.listen(port);
who can tell me what is the wrong?
i user express+socket.io in server, and i use socket.io.js in client
both server and client are in localhost
As #ebohlman mentioned
Try using
var socket = io.connect('http://localhost:8888');
in your client js instead of
var socket = new io.connect("http://localhost", 8888);
This is your issue (in the server-side code):
app.listen(port);
You need to create a separate HTTP server instead:
...
var app = express();
var server = require('http').createServer(app);
var io = require('../node_modules/socket.io').listen(server);
...
server.listen(port);
Here's my problem:
I have server A, running node.js and using socket.io for communicating with clients (web browsers). This all is running fine and dandy.
However, now that I have server B, which also needs to connect to server A through websockets, I have hit a wall. None of the node.js websocket clients I've found won't work with the socket.io on the server A.
So, this is the case I'm striving for:
.--------. .----------. .----------.
| CLIENT | <--> | SERVER A | <--> | SERVER B |
'--------' '----------' '----------'
Client-server A connection is done through socket.io
Now, Server B (running node.js) should connect to server A via websocket (in order to go through port 80). But...
Even the example code in socket.io-client module doesn't work... :/
// Connect to server
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected.');
});
The code just passes without any errors and execution ends after few seconds.
Update: Code samples
Server (which works just fine) looks like this:
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Client looks like this
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
1, 2 and 3 prints out just fine, no errors, and few seconds later the process just exits
Also, server A doesn't output anything to the log, even though I have the socket.io logging set on "everything".
For future people:
Here is 2 very simple Node.js apps that use socket.io to connect, send and receive messages between each other.
Required package is:
npm install socket.io
Node-App-1 server.js:
var io = require('socket.io').listen(3000);
io.on('connection', function (socket) {
console.log('connected:', socket.client.id);
socket.on('serverEvent', function (data) {
console.log('new message from client:', data);
});
setInterval(function () {
socket.emit('clientEvent', Math.random());
console.log('message sent to the clients');
}, 3000);
});
Node-App-2 client.js:
var io = require('socket.io-client');
var socket = io.connect("http://localhost:3000/", {
reconnection: true
});
socket.on('connect', function () {
console.log('connected to localhost:3000');
socket.on('clientEvent', function (data) {
console.log('message from the server:', data);
socket.emit('serverEvent', "thanks server! for sending '" + data + "'");
});
});
Turns out I was using old examples, for some reason, even though I triple checked them. Well, doh.
Also, it turned out that the socket.io-client is broken on latest Node (6.x.x). Managed to find an update from github for it, replaced the files and yay, everything's working!
Edit: Unfortunately I didn't save any links to working examples but after quickly skimming through the code it seems that the only changes were to the client code, which now looks like this:
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
Here is a snippet of code I wrote, it's using socket.io 1.0.6 and socket.io-client 1.0.6. The case is the following:
Server A (Socket.io Client) <---> Server B (Socket.io Server)
Server B (Server):
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res)
{
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket)
{
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Server A (Client):
console.log('1');
// Connect to server
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
If I'm using localhost:8080 only on the client server it doesn't connect.
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);
});