Answer the question
In order to leave comments, you need to log in
Why does connect fire twice?
I decided to tinker with Node.JS using a simple chat as an example. I use express and socket.io.
When a new user connects, for some reason 2 sockets are created and the information, respectively, is sent twice, while the socket id is also different, as if 2 different clients connected.
Server code:
var express = require('express');
var loger = require('log4js').getLogger();
var app = express();
var port = 3000;
server = app.listen(port);
var io = require('socket.io').listen(server);
loger.debug('App has been started...');
app.use(express.static(__dirname+'/public'));
app.get('/socket.io.js', function(req,res){
res.sendFile(__dirname+'/node_modules/socket.io-client/dist/socket.io.js');
});
app.get('/jquery.js', function(req,res){
res.sendFile(__dirname+'/node_modules/jquery/dist/jquery.min.js');
});
io.on('connection', function(socket){
var name = 'User-' + (socket.id).toString();
socket.broadcast.emit('newUser', name);
socket.emit('userName', name);
loger.info(name + ' connected to chat!');
});
var port = 3000;
var socket = io.connect('http://localhost:' + port);
socket.on('userName', function(userName){
console.log('Your nickname => '+userName);
$('textarea').val($('textarea').val() + 'Your username => ' + userName + '\n');
})
socket.on('newUser', function(userName){
console.log('New user has been connected to chat | ' + userName);
$('textarea').val($('textarea').val() + userName + ' connected!\n');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>MyFirstChat</title>
</head>
<body>
<textarea name="name" rows="8" cols="40"></textarea>
<p></p>
<input type="text" name="text" size="20">
<button type="button" name="button">Отправить</button>
<script src="/socket.io.js"></script>
<script src="/jquery.js"></script>
<script src="/main.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
[nodemon] starting `node app.js`
[2017-06-04 01:43:23.643] [DEBUG] [default] - App has been started...
[2017-06-04 01:43:24.292] [INFO] [default] - User-EuQvB85yLok7qpNoAAAA connectet to chat!
[2017-06-04 01:43:24.298] [INFO] [default] - User-gJgCheLXiMgUHeFFAAAB connectet to chat!
Your username => User-BQvRBqocCGOBQFqqAAAC
User-pYgjwfRr5WNfdmn1AAAD connected!
Your username => User-IaDaou7X3VDQSeqYAAAE
User-QLvsv9X0lAGqXnL7AAAF connected!
User-XLrvZ9xMUIBOhXDyAAAG connected!
User-KelzU_dUnANLbXEqAAAH connected!
Answer the question
In order to leave comments, you need to log in
What is a "client code"? Is it main.js?
Then why do you create twice var socket
(in "client code" and "form")?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question