This is my app.js and I want to perform both (Socket/Rest) But When I am emitting something from my client the socket is not connecting though it's showing me 101 Status in chrome ws. Can anyone help me out with what's wrong with this code?
here is my app.js
const express = require("express");
const app = express();
const indexRouter = require("./routes/index");
const apiRouter = require("./routes/api");
var server = require('http').createServer(app);
// var memcached = require('memcached');
// var mmc = new memcached('localhost:1121', {retries:10,retry:10000,remove:true});
var io = require('socket.io')(server);
const port = process.env.PORT || 3000;
const cors = require("cors");
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
app.use("/", indexRouter);
app.use("/api", apiRouter);
require("./app/router/login.router")(app);
require("./app/router/match.router")(app);
require("./app/router/competetion.router")(app);
server.listen(port,() => {
var host = server.address().address
var port = server.address().port
console.log(`Admin listening on port ${port}!`);
});
io.on('connection', (socket) => {
console.log('12---------12');
socket.on("test" , (data) => {
console.log('test', data);
})
});
// -- # socket manual --
// -- # socket ends ---
When I am emitting something its showing 101 status but nothing emitting at all
Thanks!
when considering the only problem is connecting to socket io, your code should establish a bi directional connection between the client and the server, and it does.
The 101 message means switching protocols
so if you emit a message on event named test your server will catch it.
the problem is in your client side, try any ready to use tools like this or anything else to independently test your socket io server
Related
Is there any difference between this implementation:
this.app = express();
this.httpServer = http.createServer(this.app);
this.io = socket.listen(this.httpServer);
And this one:
this.app = express();
this.server = http.createServer(this.app);
this.io = socket(this.server);
Nopers, the second is a shorthand. :)
The first is provided in the event that you want to import/export the function from your express architecture
It seems like your other question was posted after this, is this still relevant?
Ok let's see what I've done that worked. I have seperated my sockets into a config file because my app.js was getting cluttered.
app.use(express.static(path.join(__dirname, '/')));
app.use(express.static(path.join(__dirname, '/node_modules/')));
var clients = {};
var server = http.createServer(app);
var io = require('socket.io')(server);
require('./config/app.socket.js')(io);
server.listen(8001);
io.set("origins", "*:*");
So, I cut out the middleman and pass the server directly to the socket.io import. then, I pass the reference to that io server to my app.socket.js file and listen to the server on port 8001
Here is my app.socket.js initialization
module.exports = function(io){
var clients = {};
var sockets;
io.on('connection', function (socket) {
sockets = socket;
socket.on(//your socket function)
}
I try to create a real time app by socket.io.
Server side:
var express = require('express');
var io = require('socket.io');
var engine = require('ejs-locals');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
app.engine('ejs', engine);
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.redirect('/login')
});
app.use(express.static(__dirname + '/public'));
app.listen(3001);
io.sockets.on('connection', function (socket) {
console.log('Client connected...');
socket.on('send_login_data', function (data) {
console.log(data);
});
});
Client side:
var socket = io.connect('http://localhost:3001');
socket.on('connect_failed', function(){
console.log('Connection Failed');
});
socket.on('connecting', function () {
console.log('connecting...');
});
socket.on('connect', function () {
console.log('connected!');
});
I caught the next error:
GET http://localhost:3001/socket.io/1/?t=1447539302809 404 (Not Found)
As I understand, it's a handshake error.
How can I fix it?
Thanx.
First off, make absolutely sure there are no errors showing anywhere in case some module isn't installed properly.
Then, make sure you have the same version number of socket.io on client and server and that you have the server-side version installed on the server.
Then, I've seen folks have issue with this before, even when following the instructions on the socket.io web site and it's never been clear exactly what was wrong with that sequence. But, what I know is that this sequence will work:
var express = require('express');
var app = express();
var server = app.listen(3001);
var io = require('socket.io').listen(server);
See related issues: Where is my client side socket.io? and Node + Socket.io Connection issue
I don't know if this is causing the issue or not, but you are attempting to redefine the io variable when it has already been declared in this:
var io = require('socket.io');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
The second reference to io = io.listen(server) is essentially this:
var io = require('socket.io');
var app = express();
var server = require('http').createServer(app);
var io = io.listen(server);
Which is not correct Javascript. Again, may not be causing your issue, but it is not technically proper Javascript.
I'm hosting my application on openshift. I am using a custom domain. And socket.io wasn't able to download the client side script so I just used the cdn instead. But now it's not able to connect to a namespace. These are the errors it is giving me on the console log
This is my client side code on the .html page to download the client side script
<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>
and the .js index page to connect to the index namespace
var socket = io("http://www.loomius.com/index");
Here is my server side code
var express = require('express');
var app = express();
var http = require('http');
var io = require('socket.io')(http);
var mongoose = require('mongoose');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var https = require('https');
// listening on the port
app.set('port', process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || 3002);
app.set('ip', process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1");
http.createServer(app).listen(app.get('port') ,app.get('ip'), function () {
console.log("✔ Express server listening at %s:%d ", app.get('ip'),app.get('port'));
});
First instead of
var socket = io("http://www.loomius.com/index");
use this to solve issue with a need of cdn
var socket = io.connect("/");
Then on server use this instead
http = http.createServer( app ).listen( process.env.PORT, process.env.IP || "0.0.0.0", function() { // or define ip and port manually
var io = require( 'socket.io' )( http );
io.on('connection', function( socket ) {
// add event listeners here
}
});
In my application i need to connect two socket.io node applications.Using socket.io-client we can do like this.But i don't know how socket.io-client works and where to include that.
First Node Application
var express = require('express')
, http = require('http');
var app = express();
app.use(function (req, res) {
app.use(express.static(__dirname + '/public'));
});
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
io.sockets.on('connection',function(socket){
socket.on('eventFiredInClient',function(data){
socket.emit('secondNodeAppln',data);// i need to get this event in my 2nd node application how can i do this by using socket.io-client
});
});
Second Node Application
var express=require('express');
var http=require('http');
var app=express();
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
var server = http.createServer(app);
var serverAddress = '127.0.0.1';
var serverPort = 3000; //first node appln port
var clientio = require('socket.io-client');
var socket = clientio.connect(serverAddress , { port: serverPort });
socket.on('connect', function(){
console.log('connected');
});
socket.on('disconnect', function(){
console.log('disconnected');
});
var io = require('socket.io').listen(server);
server.listen(6509);
//here i need to get the 'secondNodeAppln' event raised in first node application.How can i do this.
You need to create a socket.io client in your first app:
var io = require('socket.io').listen(server); // this is the socket.io server
var clientio = require('socket.io-client'); // this is the socket.io client
var client = clientio.connect(...); // connect to second app
io.sockets.on('connection',function(socket) {
socket.on('eventFiredInClient',function(data) {
client.emit('secondNodeAppln', data); // send it to your second app
});
});
And in your second app, just listen for those events:
io.sockets.on('connection', function (socket) {
socket.on('secondNodeAppln', function(data) {
...
});
});
There's a bit of a race condition because the code above doesn't wait for a connect event on the client socket before passing events to it.
EDIT see this gist for a standalone demo. Save the three files to a directory, start the servers:
node serverserver &
node clientserver
And open http://localhost:3012 in your browser.
I have a problem with Express.io: I try to create a chat but I am not able to use the Broadcast method.
No error message, but nothing happens.
app.js
var express = require('express.io')
, index = require('./routes/index.js')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
//configure options
});
app.http().io();
app.get('/', index.index);
app.io.route('ready', function(req) {
req.io.broadcast('newUser');
});
app.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
user.js
io = io.connect();
io.emit('ready');
io.on('newUser', function(data) {
console.log("New user !!");
});
Error 2
WebSocket connection to 'ws://tchat.aws.af.cm/socket.io/1/websocket/n8Jm9Q7YYL8YdPRN4dxU' failed: Unexpected response code: 502
req.io.broadcast broadcasts to all connected clients except the client associated with the request. You should use app.io.broadcast to broadcast to all connected clients.
See the example given : https://github.com/techpines/express.io/tree/master/examples/broadcasting