express, socket.io server for browser client and node.js client - node.js

I am trying to set-up an express server with socket.io that will allow node.js clients and browser clients to connect. The browser connects with no problem. The node.js client using socket.io-client give an error:
unhandled socket.io url
Server:
var express = require('express'),
io = require('socket.io');
var app = express();
var host = 'localhost';
var port = process.env.PORT || 8080;
var server = app.listen(port, function() {
console.log('Gulp is starting my app on PORT: ' + port)
});
io = io.listen(server);
app.use('/', express.static(__dirname + '/'));
io.on("connection", function(socket) {
socket.on('clientMessage', function(jsonData, from) {
socket.emit('serverMessage', 'Got a message!');
console.log('Data being sent from', from, 'is:\n' + jsonData);
});
});
Client:
var io = require('socket.io-client')
var socket = io.connect('http://192.168.1.222:8080', {reconnect: true});
socket.emit('clientMessage', 'Hello', 'Pi-Voyager');

The issue was with the way I was requiring my dependencies. It worked on other versions but on my current version it did not.
node -v
v0.12.4
"express": "^4.13.1",
"socket.io": "^1.3.6",
"socket.io-client": "^1.3.6"
With these versions, the following code works:
Server
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 8080;
server.listen(port, function() {
console.log('Gulp is starting my app on PORT: ' + port)
});
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on("connection", function(socket) {
socket.on('clientMessage', function(jsonData, from) {
socket.emit('serverMessage', 'Got a message!');
console.log('Data being sent from', from, 'is:\n' + jsonData);
});
});
Client
var io = require('socket.io-client')
var socket = io.connect('http://10.1.0.47:8080', {reconnect: true});
socket.emit('clientMessage', 'Hello', 'Pi-Voyager');

Related

Setting up Socket io in an Express server (Error: TypeError: require(...).listen is not a function)

I have an Express server which works well, but now I want to set up Socket.io in it,
I have the error TypeError: require(...).listen is not a function
My current code (working well)
const app = express();
app.set("port", process.env.PORT || 5000);
app.listen(app.get("port"), () => {
console.log("Server running");
});
Code trying to set up Socket.io
const port = process.env.PORT || 5000;
const server = app.listen(port, () => {
console.log("Server running");
});
const io = require("socket.io").listen(server);
Can someone help me with the error above please ?
From the SocketIO documentation, to setup SocketIO with the express application, it should be:
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
io.on('connection', (socket) => {
console.log('a user connected');
});

Socket.io different pages for different ports

I have this socket.io:
var express = require('express');
var app = express();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let http2 = require('http').Server(app);
let io2 = require('socket.io')(http2);
io.on('connect', function(socket) {
app.use(express.static(__dirname + '/one_dir'));
});
io2.on('connect', function(socket) {
app.use(express.static(__dirname + '/another_dir'));
});
http.listen(4000, function(){
console.log('check *:4000');
});
http2.listen(5000, function () {
console.log('& check *:5000');
});
I am new in node.js(and in socket too), so I need that on 127.0.0.1:4000 was index.html from /one_dir, and on 127.0.0.1:5000 was index.html from /another_dir,
Can you help me to solve this problem?

couldn't print the console message

I am using c9.io.
I am using node.js, socket.io and mongodb and here is my server code :
//
// # SimpleServer
//
// A simple chat server using Socket.IO, Express, and Async.
//
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var mongoClient = require("mongodb").MongoClient;
var port = process.env.PORT;
var ip = process.env.IP;
//
// ## SimpleServer `SimpleServer(obj)`
//
// Creates a new instance of SimpleServer with the following options:
// * `port` - The HTTP port to listen on. If `process.env.PORT` is set, _it overrides this value_.
//
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);
router.use(express.static(path.resolve(__dirname)));
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);
});
//mongoose connect
mongoClient.connect("mongodb://" + ip + ":" + 27017, function(err){
if(err) throw err;
//couldnt ENTER THIS FUNCTION!!
io.sockets.on('connection', function(socket){
console.log('DONE!');
socket.on('input', function(data){
console.log(data);
});
});
});
Everything works perfectly except in that couldn't enter io.sockets.on() function..
I wrote a comment before that function..
I have tried to print message before it in the console and it works perfectly..
Any help please

socket io connecting but not emmiting

i have socket io redis and express pubsub going on, in my local host it works just fine i am using laravel events to publish to redis then socket io is supposed to emit the message, its working okay on local host but on my production server which is an ec2 vm it only gets to connect and i can see a console message 'connected' but it does not emit any events even though messages are being published to redis here is my client and server
//client
<script type="text/javascript">// <![CDATA[
var socket = io.connect('http://127.0.0.1:3000/');
socket.on('connect', function(data){
//socket.emit('subscribe', {channel:'score.update'});
console.log('connected');
});
socket.on('notification.update', function (data) {
//Do something with data
console.log('Notification Caught: ', data);
});
// ]]></script>
//server
var express = require('express'),
http = require('http'),
server = http.createServer(app);
var app = express();
const redis = require('redis');
const io = require('socket.io');
const client = redis.createClient();
server.listen(3000, 'localhost');
io.listen(server).on('connection', function(client) {
const redisClient = redis.createClient()
redisClient.subscribe('notification.update');
});
redisClient.on("message", function(channel, message) {
//Channel is e.g 'score.update'
client.emit(channel, message);
});
client.on('disconnect', function() {
redisClient.quit();
});
});
You need to change the listening of your server:
Change these:
var express = require('express'),
http = require('http'),
server = http.createServer(app);
var app = express();
const redis = require('redis');
const io = require('socket.io');
const client = redis.createClient();
And
server.listen(3000, 'localhost');
io.listen(server).on('connection', function(client){
//Code
});
To:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
And
io.on('connection, function(client){
//Code
});
server.listen(3000, function(){
console.log("Listening on :3000");
});

using socket.io in conjunction with express

I am trying to sent a basic message when users connect and disconnect. Later i want to sent parameters back and forth. But with the following code i do not get the messages print out on the server when they connect/disconnect.
When i replace io.on with server.on i can get the message 'User connected' but not user disconnected when i refresh/close the page. This however is buggy, since not everytime i refresh it logs the message and on first time it sometimes log the message multiple times.
server.js
var //io = require('socket.io'),
http = require('http'),
express = require('express');
var PORT = process.env.PORT || 8080,
HOST = process.env.HOST || 'localhost';
var app = express();
app.use(express.static(__dirname + '/views'));
app.get('/', function (req, res) {
res.sendfile(__dirname + 'index.html');
});
server = http.Server(app);
//io = io.listen(server);
var io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('User connected');
io.on('disconnect', function(socket) {
console.log('User Disconnected');
});
});
server.listen(PORT, HOST, null, function() {
console.log('Server listening on port %d in %s mode', this.address().port, app.settings.env);
});
New code:
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
var PORT = process.env.PORT || 8080,
HOST = process.env.HOST || 'localhost';
server.listen(PORT);
app.use(express.static(__dirname + '/views')); //need this for my directory structure.
app.get('/', function (req, res) {
res.sendfile(__dirname + 'index.html');
}); //Need this to call my page.
io.on('connection', function( client ){
console.log('Connected');//this does not work.
io.on('disconnect', function( client) {
console.log(client);
});
});
Try reconfiguring your socket, and server instantiation:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(process.env.PORT || 3000);
io.on('connection', function( client ) {
console.log(client) //this will now work
client.on('disconnect', function( id ) {
console.log('user with ID ' + id + ' has disconnected');
});
});
First of all you need to be sure if you have included the client side socket.io files.
<script src="/socket.io/socket.io.js"></script>
Then you need to initialize the socket connection.
<script>
var socket = io();
</script>
The above changes will be in your index.html file.
Now in server.js file,
io.sockets.on('connection', function(socket) {
console.log("User connected");
socket.on('disconnect', function() {
console.log('Got disconnect!');
});
});

Resources