I have a problem with socket.io
when I refresh the client page, sockets are increased.
for example, this is the sample code
var express = require("express"),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.get("/",(req,res)=>{
var doc=`
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var socket = io();
</script>
</head>
<body>
<h1>hello!</h1>
</body>
</html>
`
res.send(doc);
io.on("connection",function(socket){
console.log("connected!")
})
})
on the first connection, server log has 1 "connected!" message.
and refreshing the client page, the console.log() fired double. so log has 3 "connected!" messages
refreshing one more it fires triple -> 6 connected messages
and next quadriple!
I don't know why connections are multiplexed. could you help me?
Your event handler for the server-side socket you declared needs to be registered just once.
var express = require("express"),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
io.on("connection",function(socket){
console.log("connected!")
})
app.get("/",(req,res)=>{
var doc=`
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var socket = io();
</script>
</head>
<body>
<h1>hello!</h1>
</body>
</html>
`
res.send(doc);
})
Every time a request comes in from the browser, you were adding a new anonymous function as an event listener to any socket opened.
Related
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.
There are other posts asking the same question but my situation is different. The code works but with the error "failed: Connection closed before receiving a handshake response" displayed in Chrome console. I tried to strip all the code and came up with a very slimmed down code which continues to give the error. Here is the test case:
Server side:
var http = require('http');
var express = require('express');
app = express();
server = http.createServer(app);
serveFile = function (req,res) {
res.sendFile(__dirname + '/socket.html');
};
io = require('socket.io')(server);
io.sockets.on('connection',function(socket) {
socket.on('from_client',function(data) { console.log(data.name); });
socket.emit('dateFromServer', {'date': new Date()});
});
app.use(serveFile);
io.listen(server);
server.listen(2000);
Client side: (the socket.html file)
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>
</head>
<body>
<script>
var socket = io.connect();
socket.on('dateFromServer', function(data){
$('#date').text(data.date);
});
socket.emit('from_client',{'name':'John'});
</script>
<div id="date">Date will be displayed here</div>
</body>
</html>
~
Please, can someone explain what is causing the error? The messages are sent/received, from the client/server, as expected.
~
This function doesn't work in my app. I can't receive a message (socket.emit) from the server to the client (socket.on).
But i don't have this problem in the inverse (client to server).
I use cloud9 and the chat example from them works fine.
Here is my code for the server :
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);
router.use(express.static(path.resolve(__dirname, 'client2')));
io.on('connection', function (socket) {
socket.emit('hello', 'i changed'); // !!!
});
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);
});
and the code for the html page :
<html>
<head>
<title>test</title>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('hello', function (msg) { // !!!
document.innerHTML = msg;
});
</script>
</head>
<body>
<p>normal page</p>
</body>
</html>
And there is no change...
edit : with console.log either.
But the message seems sent with the socket :
Debugger listening on port 15454
info - socket.io started
Chat server listening at 0.0.0.0:8080
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized 13XpSYGuXzMpMeyFsRfO
debug - setting request GET /socket.io/1/websocket/13XpSYGuXzMpMeyFsRfO
debug - set heartbeat interval for client 13XpSYGuXzMpMeyFsRfO
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"hello","args":["i changed"]}
Can you help me please ?
You need to change
var socket = io.connect();
by
var socket = io.connect('http://0.0.0.0:8080');
var socket = io.connect() <- this should specify the domain to which you are connecting.
So i did alot in this, trying to get it to work, it sorta did but i don't work like you do, i'm a beginner and not compatible with how you code but i've figured out that the problem is the port the io is using
var io = socketio.listen(server);
or where the html is getting the connection
<script src="/socket.io/socket.io.js"></script>
to me, the html is requesting a js file in it's own dir, but it shouldn't.
When i use socket.io, i put this in the server
var client = require("socket.io").listen(8080).sockets
The main part is the listen, it listens on the port 8080 and in my html i do
var socket = io.connect("http://127.0.0.1:8080");
Which works, i'm sorry for this, i am mostly sure this isn't an answer but i've tried, i hope you get it done, even if a year and 3 months have passed.
$(function(){
var socket = io();
socket.on('hello',function(data){
$('#lblmsg').text(data.message);
});
});
this is something I am working with. in the 4th line of my code, data is passed and data.message is retrieved. but you directly equated msg with the innerhtml, on the html page(in the block you commented \!!!)
see if you are still working on it!
i've got this error requests.
The red coloured Request getting Error - 400 Bad request and it taking more then 30sec .After the error the socket work fine but it taking more time for response
In app.js the code is follows
var app = express(),
server = require('http').createServer(app);
//io = require('socket.io').listen(server);
var sockets = require('socket.io')({
'transports': ['websocket', 'flashsocket','htmlfile','xhr-polling','jsonp-polling']
});
var io = sockets.listen(server,{ resource: '/socket.io/','sync disconnect on unload':true });
io.sockets.on('connection', function(socket){
socket.emit('server_emit');
socket.on('search', function(cattype,pagNo,lang,film,iteamcat,starname){
var query={'ProductType':cattype,'Language':lang,'ProductCategory':iteamcat,'UsedBy':starname,'UsedIn':film},
field={},
options={};
db.collection("Product").find(query,field,options).toArray(function(error, Product2){
socket.emit('result',Product2);
});
});
In client side code
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('server_emit', function(){
console.log("Server emitted to Browser")
});
</script>
Please help
Try specifying the full URL as
<script src='http://localhost:3000/socket.io/socket.io.js'>
and in socket var
= io.connect('http://localhost:3000/')
I have an instant messaging chat application in the making, and am having problems getting my client to receive data from my server. Could anyone explain to me why this is happening?
app.js
var http = require("http");
var express = require("express");
var socket = require("socket.io");
var app = express();
app.use(express.static(__dirname + "/public"));
var server = http.createServer(app);
server.listen(8080);
var io = socket.listen(server);
io.sockets.on("connection", function(client) {
client.on("join", function(name) {
client.set("nickname", name);
console.log(name + " connected."); // logs name correctly
client.broadcast.emit("names", name);
});
});
index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var server = io.connect("http://localhost:8080");
server.on("connect", function(data) {
nickname = "";
while (nickname == null || nickname.trim() == "") {
nickname = prompt("Enter name");
}
server.emit("join", nickname);
});
server.on("names", function(data) {
document.getElementById("txtNames").value = data;
});
</script>
</head>
<body>
<textarea id="txtNames"></textarea>
</body>
</html>
Do you know what a broadcast is? When you broadcast a message as a result of an event from a socket, The message is emitted to all connected clients except for the socket who triggered the event. Same is your case. If you want to emit names event to your connected client then use
socket.emit("names", name); in your app.js