I have a basic node express/socket example app from the socket.io official website (linked pasted below) and i noticed that when a user connected, the 'connection' even just kept firing over and over again.
So i found a post (Socket IO chat repeating user connected) saying that there is a bug in socket.io 2.x.x and when i reverted to socket.io 1.3.7 this issue did stop, is this a confirmed bug, and we should roll back to a 1.x.x version? Or is there a new way of using socket.io that doesn't reflect on the current documentation?
My server code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
My Client side code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
My server terminal output (which just repeats forever):
a user connected
a user connected
a user connected
...
Socket.io official example:
https://socket.io/get-started/chat/
Since socket.io released version 2.x, there appears to be an issue that causes an infinitely recurring connect, disconnect, connect, disconnect and so on forever if you have mismatched versions of socket.io code on client and server.
This can be further exacerbated by client-side caching which can get the browser client stuck on an older version sometimes.
The usual fix is to make sure you're getting the socket.io client with /socket.io/socket.io.js because then the socket.io server sends the client version that matches it exactly. But, you appear to already being doing that, so I'd guess that you have some sort of browser caching problem. You can clear the browser cache manually to see if this is the issue.
Use this for the server:
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('node_modules')); // serve static files
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
And this in the HTML:
<!DOCTYPE html>
<html lang="en">
<body>
<script src="socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
The bug might be with the <script src="/socket.io/socket.io.js"></script> tag that Socket IO provides.
Related
I'm trying to create a socket in a client.js file to communicate with my server. I followed the official documentation ( https://socket.io/docs/#Using-with-Express ) with no success. Basically when I initialize my socket like this:
var socket = io();
i expect a message from my server (e.g. 'A user has connected') but nothing appear, letting me suppose that the connection never happens.
This is a project made on Glitch. I tried to follow socket.io documentation, simple examples or other questions tips. I both tried the suggested script before instantiate the socket and the cdn one.
//server.js
//dependencies
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
//listening to the port
http.listen(process.env.PORT || 3000, () => {
console.log("Listening on port " + process.env.PORT);
});
io.on('connection', function(socket){
console.log('A user has connected.');
});
//chat.html
//this is called right before </body>
<script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js'></script>
<script src='/socket.io/socket.io.js'></script>
<script src='/public/client.js'></script>
//client.js
var socket = io();
client.js is loaded as expected (and the console throws no errors) but i can't see 'A user has connected' as i'd expect.
You can check full source code here https://glitch.com/edit/#!/farlokko-advanced-node
Thanks.
UPDATE:
The problem was a wrong initialization of the passport.socketio module, which interfered with sicket.io . The main problem probably was a wrong store(memoryStore instead of mongo-store) and a wrong key for the cookie (express.sid instead of connect.sid).
Finally socket initialization was ok and had to be io.connect("host here").
As specified on the doc, you have to configure the client to connect to your localhost, and then, on the connection, you'll have your message :
<script>
var socket = io.connect('http://localhost'); // <--- HERE MAN
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I am trying to develop a live chat application using laravel. I face a problem. When I run "node index.js" , 'A connection has made' message has shown continuously in command prompt.
my index.js file is:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
app.get('/', function(request, response){
response.sendFile(__dirname+ '/index.html');
});
io.on('connection', function(socket){
console.log('A connection has made');
// socket.on('chat.message', function(message){
// io.emit('chat.message', message);
// });
});
My index.html page is:
<!DOCTYPE html>
<html>
<head>
<title>Live Chat</title>
</head>
<body>
<div class="container" id="chat">
<h1> Chat System </h1>
</div>
<script type="text/javascript">
var socket = io();
</script>
</body>
</html>
How can I solve it?
The usual reason that your client is continually trying to connect over and over again is because you have a mismatched client and server version of socket.io making them incompatible. You don't show how you load the socket.io Javascript in your web page, but if you do it like this:
<script src="/socket.io/socket.io.js"></script>
Then, you will always get the version that exactly matches your server from your server automatically (this is a route that the socket.io server automatically adds to your Express server).
If you are loading socket.io from a CDN, then you have to either switch to the above to load it from your own server or manually specify the exact same version from the CDN as you are running on the server.
If you are using it on React/NextJs
just declare these as global
import socketClient from "socket.io-client";
const SERVER = "http://127.0.0.1:8000";
const socket = socketClient(SERVER);
export default chatApplication=()=>{
//main component
}
Change port number from 3000 to 7000 for example.
I'm having trouble connecting to socket.io. With the code below, I keep getting an 'io is not defined' error on my browser console. Anyone have any idea what I'm doing wrong here? I've been poking around stackoverflow for hours, but no solution seems to work...
server side:
,db = require("../../lib/db")
,config = require("../../config")
,app = require("../index")
,io = require('socket.io')(app);
;
io.on('connection', function (socket) {
console.log('connected')
});
exports.render = function(req, res){
console.log(io)
res.render("vitron", {});
}
client side:
<!doctype html>
<html>
<head>
<title>Sockets</title>
<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>
</head>
<body>
</body>
</html>
You apparently don't have the right server-side initialization so that your server will automatically serve the /socket.io/socket.io.js file.
There are many ways to do this, but the simplest way that is documented in the socket.io documentation is to use some built-in middleware that will have the socket.io server-side library automatically intercept the request for the /socket.io/socket.io.js file and serve up the script file.
The socket.io documentation shows exactly how to do this when using express with node. If you aren't using express, then you can do it with your own middleware. Or, if you're just using plain node, you will have to either handle that route yourself or just put the /socket.io/socket.io.js file in a known location that it can be requested directly from. You can even link to it on a CDN if you want, but there is an advantage to using the built-in scheme because when/if you upgrade the socket.io library on the server, it will automatically contain a matching client-side library which is kind of nice.
I don't know exactly what your overall setup is, but here's my socket.io initialization with express 4.
var express = require('express');
var app = express();
var server = app.listen(8081, function() {
console.log(new Date().toISOString() + ": server started on port 8081");
});
var io = require('socket.io').listen(server);
I'm not able to get socket.io working on my machine with one of the very basic socket.io chat examples (just the preliminary test of it) by Guillermo Rauch locally and on cloud9 platform. I've tried socket.io in combination with both express 2.5.x and express 3 (changing the server code accordingly) and get the same behaviour using both Nodeclipse and command line running:
info: socket.io started
Socket server running # localhost on port
3000
When I visit localhost:3000 I get :
debug: served static content /socket.io
There is no handshake and perhaps the client is not connecting.
Maybe the problem is easy to see but I couldn't find an answer suiting my case here and elsewhere. Here is my environment:
Windows 7 x86 or Windows 8 64bit;
Nodeclipse upon latest stable Node (0.10.15 if I'm not mistaken);
used: google chrome, firefox, IE up to date;
tried also to serve the index page via WAMP server;
tried a lot of alternatives, which seems to suggest it is not a problem of code but belonging to something else (express not working well with the latest node installs? something wrong about environment variables?);
express seems to serve the /socket.io/socket.io.js file since it is readable through any browser when I enter localhost:3000/socket.io/socket.io.js (I don't know if this is the right test).
Here is the client code:
<!doctype html>
<html>
<head>
<title>my test</title>
<script src="/socket.io/socket.io.js"></script>
<script src="chat.js">
<link href="/stylesheets/style.css" rel="stylesheet" />
</head>
<body>
<div id="chat">
<ul id="messages"></ul>
<form id="form">
<input type="text" id="input" />
<button>Send</button>
</form>
</div>
</body>
</html>
Here is the serverside app:
var express = require('express');
var sio = require('socket.io');
var app = express.createServer(
express.bodyParser(),
express.static('public'));
app.listen(3000);
var io = sio.listen(app);
console.log('Socket server running # localhost on port ' + 3000);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log('hello');
});
});
chat.js contains:
window.onload = function() {
var socket = io.connect("http://localhost:3000");
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
};
these are the versions of socket.io and express, installed locally (express is also installed globally) via npm install command given from the nodeclipse workspace folder (c:/users/myname/workspace/nameoftheapp)
"express": "2.5.4",
"socket.io": "0.9.16"
Structure of the project
node_modules
|- [...] (all the installed folders and files]
public
|- stylesheets
--|-style.css
|- index.html
app.js
package.json
readme.md
Do I have to set something in the connection to point to my workspace correctly?
You need to use http.createServer instead of express.createServer
var express = require("express");
var http = require("http");
var app = express();
var server = http.createServer(app);
var io = require("socket.io").listen(server);
server.listen(3000, function () {
console.log("listening on port 3000");
});
I came across this question while trying to figure out how to use socket.io on Cloud9. I don't know how Cloud9 factors into your question (it's mentioned in your title though), but for me I was not able to establish the handshake from the client, and only got a debug: served static content message in the Cloud9 terminal. I eventually figured out it was the connection link in the client that was causing the problem. Setting up Express with socket.io wasn't easy either as you can get confused between the different variables like what Peter said.
Server Code:
var express = require('express'),
http = require("http"),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
server.listen(process.env.PORT || 3000, function() {
console.log('Express server started on port %s', process.env.PORT);
});
io.sockets.on('connection', function(socket) {
socket.emit('news', {
hello: 'world'
});
socket.on('my other event', function(data) {
console.log(data);
});
});
Client Code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(window.location.hostname);
socket.on('news', function(data) {
console.log(data);
socket.emit('my other event', {
my: 'data'
});
});
</script>
I used window.location.hostname so that the script would work both on the Cloud9 test server and wherever I deploy my app (Heroku in my case).
Used with Express 3.2.6 and Socket.io 0.9.13.
hey i just started tinkering with node.js and am a complete noob. i am trying to get a simple client server communication going using socket.io and express (i have never used these before).
here is my code for the app(app.js):
var sys = require('sys'),
express = require('express'),
app = express('localhost');
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.send('Hello World');
});
app.listen(3000);
var socket = require('socket.io').listen(server);
socket.on('connection', function (client){
// new client is here!
setTimeout(function () {
client.send('Waited two seconds!');
}, 2000);
client.on('message', function () {
}) ;
client.on('disconnect', function () {
});
});
and here is my code for the client(client.html):
<html>
<p id="text">socket.io</p>
<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
var socket = new io.Socket(),
text = $('#text');
socket.connect();
socket.on('connect', function () {
text.html('connected');
});
socket.on('message', function (msg) {
text.html(msg);
});
socket.on('disconnect', function () {
text.html('disconnected');
});
});
</script>
i got most of the code from:
NodeJS + socket.io: simple Client/Server example not working
and the changed it to be compatible with express 3.x
however when i run the server and open my client using chrome it tells me that it is unable
to load resource file:///socket.io/socket.io.js
i have already installed express and socket.io using npm
also i have read through atleast 20 similar posts and have not been able to find an answer
please help me. thank you
socket.io.js file needs to be served from port 3000, like localhost:3000.
So here is what you do change
<script src="/socket.io/socket.io.js"></script> to
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
Are you opening the client.html page directly from the local file system? The request for socket.io.js should look like http://localhost/socket.io/socket.io.js not file:///socket.io/socket.io.js.