I made some searches but didn't get exactly what I need. What I need is: I want to get some data generated in the client side javascript, make some manipulations on them in the server side Node.js, then return them back to javascript side. what is the simplest way to do this ?
Thanks in advance!
The simpliest way is to use socket.io
Your_project_path$ npm install socket.io
Server-side.js :
var http = require('http');
var io = require('socket.io');
httpServer = http.createServer();
httpServer.listen(8080);
var io = require('socket.io').listen(httpServer);
io.sockets.on('connection', function(socket) {
// Receive data
socket.on('my-data', function(data){
// Do something with your data
// Send modified data
socket.emit('my-modified-data', modified_data);
});
});
Client-side.js
var socket = io.connect('http://localhost:8080');
// Send your data
socket.emit('my-data', {
data-1 : 'something',
data-2 : 'something'
});
// Receive your modified data
socket.on('my-modified-data', function(modified-data){
// Do something with your new data
});
Client-side.html
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script src="client-side.js"></script>
REST.
In your client side you receive the data, modify it, send back to the server and to whatever you want.
Related
Im using a node server to get data from an websocket and I want to create my own websocket and send the data to a react app. Does anyone know any methods or packages for it.
So I do something like your question.
NODE.js side
I used the socket.io library for sending data to my react app.
So for sending I use something like this.
/*Declaration and settings up (you can replace the port)*/
const express = require('express');
const app = express();
let server = require('http').Server(app);
let io = require('socket.io')(server);
server.listen(8081); //PORT of your socket
app.listen(8080); //PORT of your API
/*If you want to do something when a user is connect you can do something like this
"topic" is a string, you can replace by what you want. Here the client (REACT) is
listening on "topic"*/
io.on('connect', (socket) => {
let messageToSend = {
"message": "Hello world!"
};
socket.emit("topic", messageToSend);
});
/*If you simply want to send something just use the io variable. like this*/
io.emit("topic", "What you whant here");
React side
For react side I used socket.io-client
import socketIOClient from "socket.io-client";
/* insert the following code in a function or where you want.*/
let client = socketIOClient("127.0.0.1:8081"); //ip of socket server
/*After define client, you define the topic you want listening and the function you
want to use as callBack. Here I just print data*/
client.on("topic", (data) => {
console.log(data)});
You can find more details on the socket.io-client and socket.io
I hope my answer can be usefull.
I am running a server using expressjs. Whenever a user accesses to one of my specific url (for this purpose, just imagine it will be https://server.com/test), I want to emit a data to another webserver using socketio, listen to the data and respond to the user with the data I have received.
Few things to note:
My server expects nothing but just an access to the https://server.com/test url.
Another server, which I want to connect using socket.io and obtain data expects me to send an argument of {"got" : "true"} to parameter called "test".
When another server receives the socket emit from my server on parameter "test" with arguments specified above, it simply replies back with an argument {"message" : "true"}
My code is quite simple and looks like this (router) :
const express = require("express");
const router = express.Router();
//const Goal = require("../models/battery_message");
const mongoose = require("mongoose");
const io = require("socket.io-client");
const host = "https://another_server.com"
const socket = io(host, {query:"email=edmund#gmail.com"});
console.log("connected");
router.get('/', function(req,res) {
socket.emit("test_me", {"got" : "true"}, function(data){
exists = data;
console.log(data);
});
});
module.exports = router;
The problem I have is whenever the user accesses my server on https://server.com/test nothing happens, as no response comes like in an infinite loop. My guess is that I need some kind of another socket.emit because another server probably emits its response to the socket too, but I might be wrong.
So to sum up, my question is, what do I need to add in order to successfully get the response from another server?
I'm new to Socket.io. Here is my problem.
I want to get the real time location of Android device. So I created a simple app to get current GPS location. And Node.js server and also Angular Admin panel.
Here is my Node.js server code.
//Some import statements are missing here. Not added.
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// Creating the socket connection.
io.sockets.on('connection', function (socket) {
socket.on('join', function (data) {
socket.join(data.id);
});
});
module.exports = function (app, express) {
var api = express.Router();
api.post('/device_location/:child_id', function (req, res) {
var child_id = req.body.child_id;
io.sockets.in(child_id).emit('new_msg', {msg: 'gps_data'}); //Sending request to registered android device.
var gps_location = ""; //Here i want to take GPS data from android client.
res.json({ type: "success", code: 200, data: gps_location }); //Then i can send the response to anyone who need that.
});
return api;
};
If this is not clear, please check this gist : https://gist.github.com/chanakaDe/123080fa5427c38c37f36afdac10be7c
First I created the socket connection. Then Android client can connect to it with unique user ID.
Then I'm sending the request to get GPS data when admin press the button from the Administration button.
io.sockets.in(child_id).emit('new_msg', {msg: 'gps_data'});
Here, child_id is the ID of android application.
Then I want to get the response from Android app and read it in server.
After reading that, I can send that to anyone asking for it.
res.json({ type: "success", code: 200, data: gps_location });
This is the normal Node.js way of sending a response.
How can we get the response to this var gps_location = ""; variable which we are getting GPS value of specific user.
Please help me on this. Tried many ways, but not good. I just need to read the response from Android client in the server and process it.
You need to emit your GPS location from Android to your server using something like :
socket.emit("gpsdata", data)
and then receive it in Node using socket.on("gpsdata", doSomething) :
io.sockets.on('connection', socket => {
socket.on("gpsdata", data => { // Receive data from one socket
io.sockets.emit('gps_location', { gps_location : data }) // Emit to everyone
})
});
https://socket.io/docs/emit-cheatsheet/
node.js WebSocket example code snippet
I have a simple node.js application using express. Now everytime a client connects to the node server I see the string 'new client connected' but I would like to know which IP the new client had.
var WebSocketServer = require('ws').Server;
var connIds = [];
var server = require('http').createServer(app).listen(80);
// set up the websocket server
var wss = new WebSocketServer( { server: server } );
wss.clientConnections = {};
// websocket server eventlisteners and callbacks
wss.on('connection', function (connection) {
console.log('wss.on.connection - new client connected');
...
See the code at:
https://github.com/qknight/relais.js/blob/master/relais.js/server.js#L159
question
The object connection has properties but I don't understand how to query them or what they are. All I want is to print the client IP and maybe, if existent, other similar properties as well.
How do I do that?
Remote IP is a property of the pre-upgrade connection:
var wss = new WebSocketServer({port: 9876});
wss.on('connection', function(ws) {
console.log(ws.upgradeReq.connection.remoteAddress);
});
i don't recall how i found it, but i know it took me a while; i wish the docs were as good as the code...
UPDATE:
WS has moved some things around, so here's an updated example of how to get the original HTTP info in current code. Note the 2nd argument to the connection event handler:
wss.on('connection', function conn(ws, req) {
var ip = req.connection.remoteAddress;
console.info(ip);
});
I know how to retrieve the client sessionID when the user connects.
But I'd like to retrieve it at any time, for example when the client clicks on something, I would like to be able to know who clicked, what their sessionID was.
socket.sessionID doesn't work, nor does socket.handshake.sessionID
For example :
I have this express route :
.get('/result/:survey', function(req, res) {
res.redirect('/result/'+req.params.survey+'/1');
})
Just before the redirection, I'd like to make the user join a socket room, and also get their sessionID. How could I possibly do that ? According to the doc, it would be socket.join('room') but I doubt socketonly represents the connection I have with the client, and not with the other clients. Maybe I'm just having trouble understanding sockets !
As of version 1.0, you get the client's sessionid this way:
var socket = io();
socket.on('connect', function(){
var sessionid = socket.io.engine.id;
...
});
I'm not sure exactly what you mean, because "when the client clicks on something" assumes that you mean 'client-side' (where you can use socket.socket.sessionid) but "store it in an array of clients" assumes you mean 'server-side' (where you can access it as socket.id).
Client-side:
var socket = io.connect();
socket.on('connect', function() {
var sessionid = socket.socket.sessionid;
...
});
Server-side:
io.sockets.on('connection', function(socket) {
var sessionid = socket.id;
...
});
I store client id's in server side event handlers simply with:
// server.js
io.sockets.on('connection', function (client) {
client.on('event_name', function (_) {
var clientId = this.id;
}
}
I'm using socket.io version 2.0.4 and you can access the client id at any point in time by using this.id in a handler. For example:
socket.on('myevent',myhandler);
function myhandler(){
console.log('current client id: '+this.id);
}
Apparently the handler function is executed in the Socket context itself, which similarly will give you access to other self-properties like client (connected Client object), request (current Request object being processed), etc. You can see the full API here https://socket.io/docs/server-api/#socket