I'm trying to connect to a socket.But I did not get the socketid on the console.Is it the right way of connecting to a socket ?Can anyone please suggest me ...
My code :
var app = express();
var dir = process.cwd();
app.use(express.static(dir)); //app public directory
app.use(express.static(__dirname)); //module directory
var server =require('http').createServer(app);
var io = require('socket.io')(server);
io.of('/socket_issue').on('connection', function (socket) {
console.log("Socket connected :"+socket.id);
socket.emit('news', { hello: 'world' });
});
client code :
var socket = io('http://localhost:8085/socket_issue');
socket.on('connect', function(){ console.log('connected to socket'); });
socket.on('error', function(e){ console.log('error' + e); });
socket.on( 'news', function( data ){
console.log(data);
});
socket.on('disconnect', function(){});
You seem to not have a server.listen() in your backend code.
I've edited the server code and it functions correctly:
var app = require('express')();
var dir = process.cwd();
var server =require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.of('/socket_issue').on('connection', function (socket) {
console.log("Socket connected :"+socket.id);
socket.emit('news', { hello: 'world' });
});
Don't forget to change the port on the front-end and it'll work as expected:
Socket connected :Y7zi7dLRxqBA5nakAAAA
Related
I am trying to solve this issue since a long but not getting an accurate answer on the stackoverflow.
We are checking on this URL.
http://amritb.github.io/socketio-client-tool/v1/
and getting the following error.
Connecting to: http://x.xxx.xxxx.xxx:5858/ with options: {"path":"","transports":["websocket"]}
Here is the code snippet.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const port = process.env.PORT || 5858;
var compression = require('compression');
app.use(compression());
io.on('connection', function (socket) {
// Socket connection for Drivers
socket.on('join', function (data) {
socket.join(data.room); // join room
console.log('New user joined on room:' + data.room);
console.log(data);
});
socket.on('disconnect', function () {
socket.leave(socket.room);
});
});
http.listen(port, function () {
console.log('Socket Listening on Port: ' + port);
});
I have tried many methods to connect socket-io client and server with express but its not working and now i do not know what could be error.
i have tried to clone example available on socket-io website still it does not show any connectivity or any functions do not emmit.
This is server.js and this is my code i have made many changes in it but not working.
var express = require('express');
var app = express();
var path = require('path');
//require socket.io
var http = require('http').createServer(app);
var io = require('socket.io')(http);
//Setup a public path to load files
app.use(express.static('public'))
//app.use(express.static(path.join(__dirname, 'public')));
//Route for index
app.get(('/'),(req,res)=>{
res.send('index');
});
//Socket connection
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
app.listen(3000,()=>{
console.log('server running on port 3000');}
);
This is index.html that the server.js is sending i only included the script
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I expect it to console log when socket is connected and disconnected and emit the functions normally.
Hello Here is your working example of socket.io
In Your server code
const express = require('express')
const app = express();
//Listen on port 3000
server = app.listen(3000, () => {
console.log('server running on port 3000');
})
//socket.io instantiation
const io = require("socket.io")(server)
//listen on every connection
io.on('connection', (socket) => {
console.log('New user connected')
socket.emit('news', { hello: 'world' });
})
Here is HTML code
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Lets say I have the following NodeJS file:
var https = require("https");
var express = require("express");
var app = express();
var options = {};
var serverPort = 8443;
var server = https.createServer(options, app);
var io = require('socket.io')(server);
var numUsers = 0;
app.get('/', function(req, res){
res.sendFile('/home/domain/index.php');
});
io.on('connection', function(socket){
socket.on('user-login', function(data){
++numUsers;
});
socket.on('new message', function (msg,room) {
console.log(msg);
});
socket.on("disconnect", function() {
--numUsers;
});
});
server.listen(serverPort, function(){
console.log("\n--------------------------------");
console.log('Node HTTPs Server');
console.log('Currently Listening on port %d',serverPort);
console.log("--------------------------------");
});
Since I can't get SNI to work on my server, I'll have to go the old fashioned way and write a script for each subdomain. But what I'd like to do is have the functions inside of the io.on('connection', function(socket) {} area to be included. So not included like a class or anything like that, but literally the code is just taken from another file and processed as if it were in that file already. A lot like PHP does includes. Is this possible?
Simplest solution would be to read code using fs.readFile[Sync] and pass it to eval inside io.on('connection', function(socket) {})
io.on('connection', function(socket){
socket.on('user-login', function(data){
++numUsers;
});
socket.on('new message', function (msg,room) {
console.log(msg);
});
socket.on("disconnect", function() {
--numUsers;
});
// eval function loaded outside io.on('connection')
eval(someFunctionBody);
// or
eval(fs.readFileSync('path/to/function/body.js'));
});
Can't you just use require?
functions.js
function myFunc() {
console.log("I am a funky func");
}
module.exports = {
myFunc,
myOtherFunc,
};
index.js
var https = require("https");
var express = require("express");
// snip
var funcs = require('./functions');
io.on('connection', function(socket){
// snip
funcs.myFunc();
});
I am using swaggerexpress middleware and swagger.
I can't get to work with socket.io
What is the proper way to attach socket.io to my server created?
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
var io = require('./api/helpers/socketio');
module.exports = app;
var config = {
appRoot: __dirname
};
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
swaggerExpress.register(app);
app.listen(10010, function () {
console.log('Application is start listening on localhost:10010');
});
io.on('connection',function(socket){
console.log("A user is connected: " + socket.id);
io.emit('message', "Welcome")
});
});
io.attach(app);
With that approach, my server is not getting up, got an error on socket.io attaching to app.
If you're okay using a different port for socket.io, you could do something like this:
var io = require('socket.io')(10011);
// Or maybe in your case:
// var io = require('./api/helpers/socketio')(10011);
io.on('connection', function(socket) {
console.log('user connected');
});
On the client you'd connect to it like this:
var socket = io('http://localhost:10011');
socket.on('connect', function() {
console.log('Socket connection established');
});
created index.js (server)
var express = require('express');
var app = express();
///creating server
var server = require('http').createServer(app);
var io = require('socket.io').listen(server, { origins:'http://nodejs-atnodejs.rhcloud.com:8000' });
below is remaining code
Routing to index.html page
app.get('/', function (req, res) {
console.log('in socket---' + res);
res.sendfile('index.html');
});
///socket connection
io.sockets.on('connection', function (socket) {
socket.on('chatmessage', function (msg) {
io.emit('chatmessage', msg);
console.log('in socket---' + data);
});
});
/// Listen to Openshift port
server.listen(process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP);
created index.html(client)
src="http://nodejs-atnodejs.rhcloud.com:8000/socket.io/socket.io.js
var socket = io.connect('http://nodejs-atnodejs.rhcloud.com:8000');
console.log('this is index page');
socket.on('chatmessage', function (data) {
console.log('chatmessage---' + data);
socket.emit('chatmessage', { my: 'data' });
});
When accessed from browser:
Problem is not getting "console.log('chatmessage---' + data);" which is inside the socket..
and keep on getting xhr-polling../t=xxxxx responses..
is my socket working properly?
Both your browser and server code is listening for an event of 'chatmessage' after connection either your browser or server should be emitting the event first and than the other should be listening such as...
// server
io.sockets.on('connection', function (socket) {
socket.emit('chatmessage', /*some data*/);
});
//client
socket.on('chatmessage', function (data) {
console.log('chatmessage---' + data);
});