How to send and receive data in sockets.io - javascript

I am stuck on something in sockets.io I want to send something to the server.js and then resend some of the data back out to everyone else connected.
So I would like to send something like
I have
userid="1"
username="dave"
message="some message"
So I would send it like :
userid:userid,
username:username,
message:message
At the moment I am only sending one paramater, 'message' like so :-
function sendmessage() {
var new_message = document.getElementById("message").value;
socket.emit('new_message', new_message);
}
and for the sever :
socket.on('new_message', function (data) {
console.log(data);
});
So I get the message ok but how do I send and receive and read the the rest and then send some of the data back out to everyone. Sorry but this is doing my head in and all the tutorials are just for sending msg.

To send a message to every socket connected : doc
io.emit('some event', { for: 'everyone' });
To answer your question about how to send multiple parameter, one way of doing this is to send an object with multiple keys.
function sendmessage() {
socket.emit('new_message', { userid, username, message });
}
socket.on('new_message', function(data){
console.log(`${data.userid} - ${data.username} - ${data.message} `);
});

Related

How to do otp verification using 2 factor

I have taken free trail from 2 factor for sending sms as otp and needs to be verified again, I am able to send the sms and also console.log the status on node side, but the issue is I am not able to send the response to client weather otp is sent or not and how could I verify it
What I have done till now
let otp = Math.floor(100000 + Math.random() * 900000) // geterating otp
const no = req.body.cPhoneNo //phone no from UI
console.log(no)
var options = {
"method": "POST",
"hostname": "2factor.in",
"port": null,
"path": "/API/V1/{{api_key}}/ADDON_SERVICES/SEND/TSMS",
"headers": {}
};
var req = http.request(options, function(res) {
var chunks = [];
res.on("data", function(chunk) {
chunks.push(chunk);
});
res.on("end", function() {
var body = Buffer.concat(chunks);
let sendData = body.toString()
console.log(body.toString())
res.json({status:body.toString}) //here I am getting error as type error json is not a function
});
});
req.write(JSON.stringify({
From: 'something',
To: no,
TemplateName: 'some Name',
VAR1: 'var 1',
VAR2: otp
// SendAt: '{OptionScheduleTime}'
}));
req.end();
I have mentioned with comment Where I am trying to send status back to client if it is send or not, but it is not taking json as throwing error .json throws type error
**One more thing I found from there website is **
I have found two url end points one to send sms with some session Id and other to get otp entered from user and verify that These are two urls
To send Otp https://2factor.in/API/V1/{api_key}/SMS/{phone_number}/AUTOGEN
To receive Otp https://2factor.in/API/V1/{api_key}/SMS/VERIFY/{session_id}/{otp_input}
api_key= The key I have got from 2factor
phone_number = receivers no
My issue is How I can use this endpoints to send the sms and to do verification, from client end I am on button click I am sending req to server via axios but in backend I have been suffering to send the msg and verify the otp
You can check out this link
Anyone out here please guide me
I don't see res.json method in node's HTTP module. Express has res.json method. Instead you should use JSON.parse. Have a look at this example from documentation.

post request only posting [object Object]

So I'm new to post/get requests and this is really my first time touching it. I'm having issues where while data is posted from my client side to server side and saved to my database, no matter what it just posts: "[object Object]"
Server side code:
//Recieve new help message
app.post("/postNewHelp", function(data){
var newHelp = data;
console.log(newHelp);
//Upload to database
pingdb.all(`UPDATE userHelp SET privateMessage = "${newHelp}"`);
});
Client side:
//send new help message
function sendNewHelp() {
var newHelpMessage = document.getElementById("userHelpSetting").innerHTML;
console.log (newHelpMessage);
//Send to serverside
$.post("/postNewHelp", newHelpMessage), function(data){
console.log(data);
}
alert("Done! your changes should now be in effect.");
}
Any help is appreciated, thanks!
Try to name your data like that.
$.post("/postNewHelp", {helpText:JSON.stringify(newHelpMessage)}), function(data){
console.log(data);
}
And in your server side you can find your date like that.
var helpText = data.helpText
But, while you are using jQuery, don't hesitate to use that in your client side.
var newHelpMessage = $("#userHelpSetting").text();
Please feel free to read about JSON Stringify and JSON parse
Check the client side code. If possible send the parameter as json object as below
function sendNewHelp() {
var newHelpMessage = document.getElementById("userHelpSetting").innerHTML;
console.log (newHelpMessage);
//Send to serverside
$.post("/postNewHelp", {"help": newHelpMessage}, function(data){
console.log(data);
alert("Done! your changes should now be in effect.");
});
}
Now on the server side
//use the body parser
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended: true
}));
app.post("/postNewHelp", function(req, res){
var newHelp = req.body.help;
console.log(newHelp);
//Upload to database
pingdb.all(`UPDATE userHelp SET privateMessage = "${newHelp}"`);
});

Flask-SocketIO: Sending messages back to client

I am currently trying to implement a Twitter Stream using Twitter's Streaming API and I am using Flask-SocketIO for use in Python. Now I am able to send an emit to trigger a function in Flask which calls the Twitter API based on some keyword, but I want the text from the stream back to the JavaScript front-end which hasn't been too successful. I am able to send, for instance, a message like "Hi" if I listen on 'message', but I've tried to send JSON back to no avail.
My Flask function for this is:
#socketio.on('my event')
def handle_my_custom_event(json):
print('received json: ' + str(json))
r = api.request('statuses/filter', json)
for item in r.get_iterator():
if 'text' in item:
print(item['text'])
json_data = {'data': item['text']}
send(json_data, json=True)
JSON in this case is {'track':'$AAPL'} so fetches each tweet about Apple as it happens. item['text'] is the string of the tweet text. I've tried using send, also tried using emit('my response',json_data) and listened for 'my response' but I'm not sure I'm doing all of this right.
My front-end script for this currently looks like this:
$(document).ready(function() {
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
socket.emit('my event', {'track': '$'+data_prices[0]['symbol'].toString()}, function(data){
console.log(data);
if (data.error)
console.log('Something went wrong on the server');
if (data.ok)
console.log('Event was processed successfully');
});
});
});
but I receive no console logs, nothing.
What would I have to do to receive the json_data object in my front-end script and have it log to the console?
UPDATE: I've managed to get them coming in when I emit them to an event 'my response' but it only seems to log to the console when I shut down the server. Is there a way to keep this running as a stream to the console so I can use the data in the front-end?
I discovered that my problem was the listener for the response was not properly set up so I changed the Flask function to:
#socketio.on('my event')
def handle_my_custom_event(json):
print('received json: ' + str(json))
r = api.request('statuses/filter', {'track':'pizza'})
for item in r.get_iterator():
if 'text' in item:
print(item['text'])
json_data = {'data': item['text']}
emit('my response',json_data)
then in the front-end I had:
$(document).ready(function() {
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
socket.emit('my event', {'track': '$'+data_prices[0]['symbol'].toString()}, function(data){
console.log(data);
});
});
socket.on('my response', function(data){
console.log(data);
});
});
The issue is that Flask is by default synchronous, and to have the messages come in as and when they happen, when creating the SocketIO app, asynchronous mode has to be explicitly defined:
socketio = SocketIO(app, async_mode="threading")

accessing data out of socket block

I am doing the client-server application vie net module. Client send me data, depending upon the type of data i have to send back response from server. I am doing via socket.on() method. Problem is when i receive data from client i convert it to string to check what has the client sent. Depending upon it i set the array and then want to pass back to client server in json form. The problem is when i set the array in the block the data in it isn't available. It shows me empty array.Below is my code snippet:
var server = net.createServer(
function(socket){
console.log("Client connection...");
socket.on('end', function(){
console.log("Client disconnected...");
});
// process data from client
socket.on('data', function(data){
//console.log(" Received:", data.toString());
a=data.toString();
//console.log(a);
if(a=="lookupByLastName('Smith')")
{
arr= employees.lookupByLastName('Smith');
flag=true;
console.log("hey" +arr.length);
}
console.log("check1:"+arr.length+":"+flag); // here array has data
});
console.log("check2:"+arr.length+":"+flag); // array length has no data
// send data to client
socket.write("Data"+JSON.stringify(arr); ); // arr contains no data
});
The problem is that you call socket.write on initialization, i.e. when data may not have been received. You should call socket.write after you get the data. See modified code below:
var server = net.createServer(
function(socket){
console.log("Client connection...");
socket.on('end', function(){
console.log("Client disconnected...");
});
// process data from client
socket.on('data', function(data){
//console.log(" Received:", data.toString());
a=data.toString();
//console.log(a);
if(a=="lookupByLastName('Smith')")
{
arr= employees.lookupByLastName('Smith');
flag=true;
console.log("hey" +arr.length);
socket.write("Data"+JSON.stringify(arr); ); // Here the array will have the data
}
console.log("check1:"+arr.length+":"+flag); // here array has data
});
});

Pass message from Controller to AJAX script in View

I'm using jQuery and AJAX in the View to send some data to the Controller that writes it to the database. On success I show a div tag with a green background with "OK" text. But what if I do a check first in the Controller if the data already exist in the database, then I would like to alert the user that the data could not be added. Is there a way to pass some kind of message back to the AJAX script?
I guess the success option is just a confirm of contact with the Controller and not a real confirm that everything is OK and the data has been added to the database!?
What action in the Controller would cause the error function in the AJAX code to run?
Finally I just wonder what kind of return I should use since I'm actually not returning anything?
My script in the View:
$.ajax({
url: "/Orders/AddOrder",
type: "GET",
cache: false,
data: { a: order, b: seller },
success: function () {
console.log('AJAX successful');
// Show confirm message
$(".messageOk").show();
$(".messageOk").text("OK").delay(2000).queue(function () {
location.reload();
});
},
error: function () {
????
},
complete: function () {
????
}
});
Controller:
// Add new Resource
public ActionResult AddOrder(int a, int b)
{
var order = new Order
{
OrderNumber = a,
Seller = b
};
db.Orders.Add(order);
db.SaveChanges();
//return new EmptyResult();
return RedirectToAction("Index", "Home"); // ??????
}
You could return the appropriate HTTP status code from your controller action: 409 Conflict.
if (the resource already exists in db) {
return new HttpStatusCodeResult(HttpStatusCode.Conflict);
}
which will trigger the error AJAX function in which you could check whether you are in this situation and act accordingly:
error: function(jqXHR) {
if (jqXHR.status == 409) {
alert('Sorry but this resource already exists');
}
}
As you can see this way it's up to the view to decide what error messages to display based on proper HTTP status codes returned from the server. This way you are not cluttering the server with view logic.
Along with the correct response status code, you can also pass in your response body error messages from the server may be as JSON string or plain string

Categories