Socket.io: io.connect doesn't work - javascript

I use node.js with express.js framework. I Tried connect to server using io.connect on client side.
Template:
html
head
title Example chat
script(src="http://code.jquery.com/jquery-latest.min.js")
script(src="http://cdn.socket.io/stable/socket.io.js")
script(src="javascripts/chat.js")
body
form
input(type="text" name="msg")
input(type="submit")
It's chat.js:
var socket = io.connect('//localhost:8080');
app.js socket.io require:
var io = require('socket.io').listen(8080);
Firebug gives an error:
TypeError: io.connect is not a function
What is it? How to fix it?
Thanks you.

Server-side
var express = require('express');
var http = require('http');
var io = require('socket.io');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
server.listen(app.get('port'), function(){
console.log("✔ Express server listening on port %d in %s mode", app.get('port'), app.settings.env);
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Client-side
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Then if you're wondering where that socket.io.js is found, it's automatically generated.

Related

Node js - Socket.io - client is not connecting to socket.io server

I am trying to connect to a socket.io-client using this as my server.js:
var express = require('express');
var app = express();
var server = app.listen(3001);
var io = require('socket.io').listen(server);
app.get('/input', function(req, res){ // This is because in the server the port 3001 is open and I only can use the route 'input' to connect to the node server
res.send('Hello world');
});
io.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
And in my client file:
var socket = io.connect('https://urlofthepage:3001', {reconnect: true});
socket.on('connect', function() { console.log('connect'); });
// or (I tried with both)
var socket = io.connect('https://urlofthepage:3001/input', {reconnect: true});
socket.on('connect', function() { console.log('connect'); });
But when I go to urlofthepage/input show me
Hello world
but in the node server not show anything like
Client connected.
And in the page where I have the client.js file the console show me
3001/socket.io/?EIO=3&transport=polling&t=MBSSeZj net::ERR_CONNECTION_TIMED_OUT
Edit: It's on an online server, which has a wordpress installed, and my socket.io.js script is urlofpage/socket.io/socket.io.js
AND (I don't know if this matters, it is a test server, and the url has https, but it indicates that it is not secure, we have to change it)

Socket.IO Client How to Connect?

I was following the second example here:
https://github.com/socketio/socket.io-client
and trying to connect to a website that uses websockets, using socket.io-client.js in node.
My code is as follows:
var socket = require('socket.io-client')('ws://ws.website.com/socket.io/?EIO=3&transport=websocket');
socket.on('connect', function() {
console.log("Successfully connected!");
});
Unfortunately, nothing gets logged.
I also tried:
var socket = require('socket.io-client')('http://website.com/');
socket.on('connect', function() {
console.log("Successfully connected!");
});
but nothing.
Please tell me what I'm doing wrong. Thank you!
Although the code posted above should work another way to connect to a socket.io server is to call the connect() method on the client.
Socket.io Client
const io = require('socket.io-client');
const socket = io.connect('http://website.com');
socket.on('connect', () => {
console.log('Successfully connected!');
});
Socket.io Server w/ Express
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = process.env.PORT || 1337;
server.listen(port, () => {
console.log(`Listening on ${port}`);
});
io.on('connection', (socket) => {
// add handlers for socket events
});
Edit
Added Socket.io server code example.

How to make remote websocket connection to nodejs server on heroku

I'm trying to connect to a nodejs server over a websocket connection but can't get anything to work.
My server.js looks like this:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io', {
transports: ['websocket']
})(http);
var server_port = process.env.PORT || 8080
var server_ip_address = process.env.IP || '0.0.0.0'
app.listen(server_port, server_ip_address, function () {
console.log('listening on ' + server_ip_address + ":" + server_port);
});
My client.js (running on a raspberry pi also running nodejs) is:
var io = require('socket.io-client');
var socket = io.connect('http://<app-url>',
{
reconnect: true,
transports: ['websocket']
}
);
socket.on('connect', function(socket) {
console.log('Connected!');
});
I've also tried on openshift v2 (ports 8000 and 8443) and v3 and no luck there.
If anyone has done this recently please let me know how, thanks!
When debugging the client I get the message:
engine.io-client:socket socket close with reason: "transport error"
and on the server:
heroku[router]: at=error code=H13 desc="Connection closed without response"
It looks like a strange bug that happens sometimes, you should be able to get through by adding the path of your client library in the options like so :
var socket = io.connect('http://<app-url>:8080',
{
reconnect: true,
transports: ['websocket'],
path: "/lib/socket.io.js" //use the relevant path for your file
}
);
But you seem to be using the default options anyway, so you could just do :
var socket = io.connect();
Ok, it's working now. I modified the example in the heroku docs
I'm not quite sure why my server config doesn't work, but the following does work:
server.js
var express = require('express');
var socketIO = require('socket.io');
var path = require('path');
var PORT = process.env.PORT || 3000;
var app = express();
var server = app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
var io = socketIO(server);
io.on('connection', (socket) => {
console.log('Client connected');
socket.on('disconnect', () => console.log('Client disconnected'));
});
client.js (xShirase was right in saying I needed the correct path here...)
var io = require('socket.io-client');
var socket = io.connect('https://<url>',
{reconnect: true, transports : ['websocket'], path: '/socket.io'});
socket.on('connect', function (socket) {
console.log('Connected!');
});

Express nodejs socket.io with cordova

I'm trying to implement socket.io on my server. This server is an API (express nodejs).
The server side is simple, but for the client side I'm using phonegap/cordova.
I don't use a phone to test what I do, I use my browser (chrome).
Si this the server side :
var express = require('express'); // call express
var app = express(); // define our app using express
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
io.emit('text', 'wow. such event. very real time.');
});
for now, this is simple,
But for the client side I am completely confuse (cordova phonegap),
This is what I have :
index.html
<script type="text/javascript" src="http://cdn.socket.io/socket.io-1.0.3.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
console.log('send')
socket.emit('my other event', { my: 'data' });
});
</script>
Nothing appears but errors like
GET http://localhost:8080/socket.io/?EIO=2&transport=polling&t=1462638049681-3 net::ERR_CONNECTION_REFUSED
and nothing on my server
any ideas to help me ? thanks :)
Your server is not listening on port 8080. That's why when you try to connect from browser to var socket = io.connect('http://localhost:8080');, it shows 'Connection Refused'.
This edit would work for you.
var express = require('express'); // call express
var app = express(); // define our app using express
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
io.emit('text', 'wow. such event. very real time.');
});
//Now server would listen on port 8080 for new connection
http.listen(8080, function(){
console.log('listening on *:8080');
});

Socket functions in a separate file in Express server

I simply want to implement my socket functions in a separate file (i.e not in the express server implementation) like (/routes/sockets.js). How can I do that?
My express server:
var express = require('express')
, routes = require('./routes')
, socket = require('./routes/socket.js')
, http = require('http')
, path = require('path');
,app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
The socket listener (currently in the same file as above server implementation)
sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) { //event on client
console.log('my other event data ' + data);
});
});
Ok I figured it out by my self. You can call the required sources using
io.sockets.on('connection', require('./routes/socket'));

Categories