How to send info from client back to the same connection - javascript

I need help with socket.io. I want the client to send info that the server and then the server sends it back to the same client, not all of them. Here is how the code is set up:
Client
var socket = io.connect();
socket.on("receive", function(data){
console.log(data);
});
socket.emit("send", "hello");
Server
socket.on("send", function(data){
io.sockets.emit("receive", data);
});
This way makes "hello" get logged to all the connections. Is there a way so that only the one that sent it receives?

Change to:
socket.on("send", function(data){
socket.emit("receive", data);
});
io.sockets.emit() is an explict directive to send to all connected sockets whereas socket.emit() only sends to the one socket.

Related

Send response multiple times?

I have a little problem.
I have a node application on a server, that serves a website as control panel for a client based application.
Example:
You click a link on the site
A http request triggers the server to send a command via socket to the client
The client executes this command
The client sends the output of the command back to the server (socket)
That works fine, on time. The second time the server crashes because the header is already sent.
//Comand comes in
app.get('/create/:id/:package', function (req, res) {
if (io.sockets.connected[req.params.id]) {
//Command is sent to client
io.sockets.connected[req.params.id].emit('control', {type: 'create', packageName: req.params.package});
//Output is coming back
socket.on('createOutput', function (data) {
//Response sent back to http request (works once)
res.send(data);
});
}
});
Is there any way to work around this behavior?
You can send the data only once with socket.once:
socket.once('createOutput', function (data) {
//Response sent back to http request (works once)
res.send(data);
})

socket.io emit/broadcast to every client

I can not find out how to emit from the client or an other NodeJS file to every client.
Emitting to the server worked, but not to every other client.
Servercode:
var io = require('socket.io').listen(app.listen(8080));
io.on('connection', function (socket) {
socket.on('playerData', function(data) {
console.log(data);
});
});
Clientcode:
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script>
var socket = io('http://localhost:8080');
socket.on('playerData', function(data) {
console.log(data);
});
</script>
I am using Node.JS - Jade, Express, Socket.io (and AngularJS, but not in this part of the code)
The Serverside console.log is being called when I call my emit function, but on the Clientside nothing happens.
Currently using Chrome as my browser.
You need to emit from the client to the server and then broadcast that message from the server to each client.

socket.io not working on several clients

I'm trying to build a simple chat client and am having some issues getting it working across multiple clients. Chances are I've missed something really simple. When I send something from one client it is logged in that client but not in any others.
Server:
var io = require('socket.io').listen(5000);
io.sockets.on('connection', function (socket) {
socket.on('send', function (data) {
socket.emit('receive', data);
});
});
Client:
var socket = io.connect('http://localhost:5000');
socket.on('receive', function(data){
console.log("Data received at " + new Date() + ": " + data);
});
The socket variable that gets passed to your callback function is a handle on the client that connected, so socket.emit is behaving correctly, i.e. it should only send to the client that originated it.
Try:
socket.broadcast.emit('receive', data);
to send to everybody except the originating client, or
io.sockets.emit('receive', data);
to send to all clients including the originator.
You want to emit on all sockets, not just the one that sent the message.
So you should be using:
io.sockets.emit('recieve', data);
This is assuming that you aren't logging the data on the sending client before sending it to the server. In that case you'll want to use:
socket.broadcast.emit('recieve', data);
Which will send the message to all connected clients except the sender.
See here for reference on Socket.io
Edit: Trevor beat me to it. However, for some additional clarification: io.sockets is the same as io.of(''). Which is handy to know for when you start using namespaces in a scoket.io app.

Socket IO Server to Server

Is it possible for a server to connect to another using Socket.IO and be treated like a client?
And have it join rooms, recieve io.sockets.in('lobby').emit(). And more?
The first server is also listening for connections/messages as well.
Hey Brad, here's my full .js app below for reference:
var io = require("socket.io").listen(8099);
io.set('log level', 1);
io.sockets.on("connection", function (socket) {
console.log('A Client has Connected to this Server');
//Let Everyone Know I just Joined
socket.broadcast.to('lobby').emit("message",'UC,' + socket.id); // Send to everyone in Room but NOT me
socket.on("message", function (data) {
//Missing code
socket2.send('message,' + data); //Forward Message to Second Server
});
socket.on("disconnect", function (data) {
//Send Notification to Second Server
//Need to figure out later
//Send Notification to Everyone
socket.broadcast.emit("message",'UD,' + socket.id ); //Send to Everyone but NOT me
//Remove user from Session ID
arSessionIDs.removeByValue(socket.id);
//Send Notification to Console
console.log("disconnecting " + arRoster[socket.id][1]);
});
});
var io_client = require( 'socket.io-client' );
var socket2 = io_client.connect('http://192.168.0.104:8090');
socket2.on('connect', function () {
socket2.emit('C3434M,Test');
});
Yes, absolutely. Just use the Socket.IO client in your server application directly.
https://github.com/LearnBoost/socket.io-client
You can install it with npm install socket.io-client. Then to use:
var socket = io.connect('http://example.com');
socket.on('connect', function () {
// socket connected
socket.emit('server custom event', { my: 'data' });
});
I realize this is an old post, but I was working on something similar and decided to come back and contribute something as it got me thinking.
Here's a basic Client -> Server 1 -> Server 2 setup
Server #1
// Server 1
var io = require("socket.io").listen(8099); // This is the Server for SERVER 1
var other_server = require("socket.io-client")('http://example.com:8100'); // This is a client connecting to the SERVER 2
other_server.on("connect",function(){
other_server.on('message',function(data){
// We received a message from Server 2
// We are going to forward/broadcast that message to the "Lobby" room
io.to('lobby').emit('message',data);
});
});
io.sockets.on("connection",function(socket){
// Display a connected message
console.log("User-Client Connected!");
// Lets force this connection into the lobby room.
socket.join('lobby');
// Some roster/user management logic to track them
// This would be upto you to add :)
// When we receive a message...
socket.on("message",function(data){
// We need to just forward this message to our other guy
// We are literally just forwarding the whole data packet
other_server.emit("message",data);
});
socket.on("disconnect",function(data){
// We need to notify Server 2 that the client has disconnected
other_server.emit("message","UD,"+socket.id);
// Other logic you may or may not want
// Your other disconnect code here
});
});
And here's Server #2
// Server 2
var io = require("socket.io").listen(8100);
io.sockets.on("connection",function(socket){
// Display a connected message
console.log("Server-Client Connected!");
// When we receive a message...
socket.on("message",function(data){
// We got a message. I don't know, what we should do with this
});
});
This is our Client, who sends the original message.
// Client
var socket = io('http://localhost');
socket.on('connect', function(){
socket.emit("message","This is my message");
socket.on('message',function(data){
console.log("We got a message: ",data);
});
});
I am making this post a Community Wiki so that someone can improve this if they feel like it.
The code has not been tested, use at your own risk.
I had the same problem, but instead to use socket.io-client I decided to use a more simple approach (at least for me) using redis pub/sub, the result is pretty simple.
You can take a look at my solution here: https://github.com/alissonperez/scalable-socket-io-server
With this solution you can have how much process/servers you want (using auto-scaling solution), you just use redis as a way to forward your messages between your servers.

NodeJS email proxy

I am trying to proxy emails via NodeJS in order to do very custom processing on outgoing emails on our test server.
This is what I have:
var net = require('net');
var server = net.createServer({allowHalfOpen: true}, function(socket) {
console.log('New connection established.');
socket.setEncoding('utf8');
socket.on('data', function(data) {
console.log(data);
});
socket.on('end', function() {
console.log('Connection closing.');
});
socket.resume();
});
server.listen(25);
It does not yet process the emails, because it simply doesn't even work. I get the connection established message in console every time I send an email, but the data event never gets fired. I'm not sure if it's that the data already came before I bound the event listener, or whether I'm supposed to talk to the client first (HELO?).
I'm trying to access the email contents, basically.

Categories

Resources