Answer the question
In order to leave comments, you need to log in
Socket.io on Node.js. A simple example, but the exchange is incorrect. Why?
Hi everybody. I take the simplest, minimal example. In fact, from the manual.
Server:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(3000);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
console.log('client connect');
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
var socket = require('socket.io-client')('http://localhost:3000');
socket.on('connect', function() {
console.log('connected to server');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
});
Answer the question
In order to leave comments, you need to log in
The connect
event on the client fires every time the code it connects to the server.
When you restart the server, the connection is broken, and then connect again .
Every time you connect , you hang up socket.on('news'... - you don't need to do that.
var socket = require('socket.io-client')('http://localhost:3000');
socket.on('connect', function() {
console.log('connected to server');
});
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question