so I am developing an small application that need a bi-directional channel to transmit data between client and server.
I have no problem to send sata from server to client. Works just fine. But , the other way around is not working. for some reason , sending data from client to client does not work.
here is the client.js
let io = require('socket.io-client');
let socket = io.connect("http://localhost:5000/", {
reconnection: false
});
socket.on('connect', function() {
console.log('Connected to server');
socket.emit('data', 'data is emitted !')
});
and here is server.js :
var io = require('socket.io').listen(process.env.port||5000);
io.on('connection',function () {
console.log('client connected');
io.on('data',function (data) {
console.log(`data received is '${data}'`)
})
});
What am I missing ?
The server code needs to listen for incoming events from a particular socket.on(), not io.on(). io is the server. It gets notified of new connections, but not of individual messages on a given connection. You have to listen to events on a particular socket to receive data from the client.
So, change to this (change io to socket in one place and add socket argument to the io.on('connection', function(socket) ()); handler (see the two places that socket was added below):
const io = require('socket.io').listen(process.env.port||5000);
io.on('connection', function(socket) {
console.log('client connected');
// listen for incoming data msg on this newly connected socket
socket.on('data',function (data) {
console.log(`data received is '${data}'`)
});
});
Note: the addition of socket in two places.
Related
I know that messages can be sent outside the socket connection code block. How can I receive messages from the client the same way?
// Create socket.io server attached to current HTTP server
var io = require('socket.io')(server);
// When connection is made, set up some definitions for the server's connections
io.on('connection', (socket) => {
console.log('Local server connected...');
socket.on('disconnect', () => {
console.log('Local server disconnected...');
});
// I can receive messages here
socket.on('sendToRemote', function (data) {
console.log(data);
});
});
// Messages can be received outside the socket code using this syntax:
io.of('/').emit('runCamera', "Client connected...");
// I can't receive messages here...
// How can the server receive messages outside the socket code?
// I tried using the code below but it didn't work.
// Syntax compiles but doesn't work like the one above.
io.of('/').on('sendToRemote', function (data) {
console.log(data);
});
You need to have a socket to get messages from. You can emit to a room because it's tracking all the sockets connected to that room.
So to get messages only in a specific room:
io.of('/').on('connection', function (socket) {
socket.on("sendToRemote", function (data) {
console.log(data);
});
});
I am trying to connect to a socket.io-client using the following code:
Server:
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Client:
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
I don't get the Connected console log or Client Connected console log and I don't know why! The code sample is taken from another question posted: Link and I don't see any solution to the problem...
Use the same version of socket io client and server. It will work perfectly.
Also you need to add protocol with path.
change
var socket = io.connect('localhost:8080', {reconnect: true});
to
var socket = io.connect('http://localhost:8080', {reconnect: true});
Assuming you are using a socket.io version greater than 1.0, on the server, change this:
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
to this:
// Add a connect listener
io.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
See the socket.io documentation reference here.
You don't want to be listening for this event only on already connected sockets. You want to listen for this event on any socket, even a newly created one.
Also, be very careful when reading socket.io code in random places on the internet. Some things changed significantly from v0.9 to v1.0 (I don't know if this was one of those things or not). You should generally always start with the socket.io documentation site first since that will always represent the latest version. Then, if looking at other internet references, make sure you only use articles that are later than mid-2014. If you don't know the vintage of an article, it's best not to rely on it without corroboration from a more recent article.
you can use localhost. It works for me as well. You must use your ip address and port that works for you
I have this simple TCP server:
var net = require('net');
var server = net.createServer(function (socket) {
socket.on('connect', function() {
console.log("New client!");
});
});
server.listen(8000, function(){
console.log("server running...")
});
and then I have another file as client.js:
var net = require('net');
var client = net.connect({port: 8000},
function() {
console.log('client connected');
});
client.on('error', console.error);
I run server in one terminal window and then I run client in other window and expect to see server log "New Client". Although, that doesn't happen. So, when is the 'connect' event exactly emitted?
net.createServer sets the given function as a listener to the connection event.
In other words, on the server side, the socket is already connected when you get the callback, and the event you're trying to listen to isn't emitted on an already connected socket.
I made a different test. The server object has "timeout" property. When you call the follow code:
server.setTimeout(500); //Now after 0,5 second you can call "connection" event.
The default value is 120000.
But, I still have no idea what this change will cause.
How do i send a message to a specific client, more specifically, the client that has just connected to the app without broadcasting to the rest of the visitors that are already on the site?
io.sockets.on('connection', function(client) {
});
Seems to broadcast to everyone every time a new visitors connects.
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('greetings', { greeting:'hello, new visitor' });
socket.on('greetingFromVisitor', function (data) {
console.log(data);
});
});
Here's my problem:
I have server A, running node.js and using socket.io for communicating with clients (web browsers). This all is running fine and dandy.
However, now that I have server B, which also needs to connect to server A through websockets, I have hit a wall. None of the node.js websocket clients I've found won't work with the socket.io on the server A.
So, this is the case I'm striving for:
.--------. .----------. .----------.
| CLIENT | <--> | SERVER A | <--> | SERVER B |
'--------' '----------' '----------'
Client-server A connection is done through socket.io
Now, Server B (running node.js) should connect to server A via websocket (in order to go through port 80). But...
Even the example code in socket.io-client module doesn't work... :/
// Connect to server
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected.');
});
The code just passes without any errors and execution ends after few seconds.
Update: Code samples
Server (which works just fine) looks like this:
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Client looks like this
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
1, 2 and 3 prints out just fine, no errors, and few seconds later the process just exits
Also, server A doesn't output anything to the log, even though I have the socket.io logging set on "everything".
For future people:
Here is 2 very simple Node.js apps that use socket.io to connect, send and receive messages between each other.
Required package is:
npm install socket.io
Node-App-1 server.js:
var io = require('socket.io').listen(3000);
io.on('connection', function (socket) {
console.log('connected:', socket.client.id);
socket.on('serverEvent', function (data) {
console.log('new message from client:', data);
});
setInterval(function () {
socket.emit('clientEvent', Math.random());
console.log('message sent to the clients');
}, 3000);
});
Node-App-2 client.js:
var io = require('socket.io-client');
var socket = io.connect("http://localhost:3000/", {
reconnection: true
});
socket.on('connect', function () {
console.log('connected to localhost:3000');
socket.on('clientEvent', function (data) {
console.log('message from the server:', data);
socket.emit('serverEvent', "thanks server! for sending '" + data + "'");
});
});
Turns out I was using old examples, for some reason, even though I triple checked them. Well, doh.
Also, it turned out that the socket.io-client is broken on latest Node (6.x.x). Managed to find an update from github for it, replaced the files and yay, everything's working!
Edit: Unfortunately I didn't save any links to working examples but after quickly skimming through the code it seems that the only changes were to the client code, which now looks like this:
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
Here is a snippet of code I wrote, it's using socket.io 1.0.6 and socket.io-client 1.0.6. The case is the following:
Server A (Socket.io Client) <---> Server B (Socket.io Server)
Server B (Server):
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res)
{
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket)
{
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Server A (Client):
console.log('1');
// Connect to server
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
If I'm using localhost:8080 only on the client server it doesn't connect.