Sending udp packets using chrome.socket.udp - sockets

I was creating a chrome extension in which i am using chrome.socket.udp. I am following this tutorial but i don't see any data sent.
This is my code..
//var socketId;
var address = "127.0.0.1";
var port = 6454;
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2);
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return bufView;
}
function sendPackets(){
console.log("sending packets");
chrome.sockets.udp.create({}, function(socketInfo) {
// The socket is created, now we can send some data
var socketId = socketInfo.socketId;
console.log(socketId);
chrome.sockets.udp.send(socketId, str2ab("hello"),
'127.0.0.1', 1337, function(sendInfo) {
console.log("packets sent");
console.log("sent " + sendInfo.bytesSent);
});
});
}
document.getElementById('send').addEventListener('click', sendPackets);
this is the output i am getting in console...
sending packets background.js:16
165 background.js:20
And there is no sign of sent data ....plz help...

Related

Using socket to cmmunicate node app to c# service

[Sorry for my bad English]
Hi!
I have to communicate between a node.js application [client side] and c# application [server side].
Each side sends pings to the other, on TCP protocol.
I Successed to create both client and server side, but I have to problems:
after the first ping from the client to the server, the client throws an error:
This socket has been ended by the other party
What i'm doing wrong?
The server reads the incomeing pings into a large buffer.
When I decode it to string, I get string with length of 4096.
How I read the excact message length?
This is the server side code: [c#, .NET 6]
using System.Net;
using System.Net.Sockets;
using System.Text;
Console.WriteLine("Start...");
CancellationTokenSource cts = new();
TcpListener listener = new(IPAddress.Any, 11111);
try
{
listener.Start();
Console.WriteLine("Listining...");
var clientCounter = 0;
var ct = cts.Token;
while (!ct.IsCancellationRequested)
{
using TcpClient client = await listener.AcceptTcpClientAsync(ct)
.ConfigureAwait(false);
using NetworkStream stream = client.GetStream();
_ = PrintUploadedData(stream, ct);
_ = PushData(stream, ct);
clientCounter++;
Console.WriteLine("New client ({0}) connected", clientCounter);
}
}
finally
{
cts.Cancel();
listener.Stop();
}
async Task PrintUploadedData(NetworkStream stream, CancellationToken ct)
{
var buf = new byte[4096];
while (!ct.IsCancellationRequested)
{
var timeout = CancellationTokenSource.CreateLinkedTokenSource(
ct,
new CancellationTokenSource(TimeSpan.FromMinutes(3)).Token);
try
{
var amountRead = await stream.ReadAsync(buf, timeout.Token);
if (timeout.IsCancellationRequested)
{
Console.Error.WriteLine("No Message.");
break;
}
if (amountRead == 0) break; //end of stream.
var message = Encoding.UTF8.GetString(buf);
Console.WriteLine(message);
}
catch (OperationCanceledException)
{
Console.Error.WriteLine("Time out");
break;
}
}
}
async Task PushData(NetworkStream stream, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
var messageToSend = DateTime.Now.TimeOfDay.ToString();
var messageBytes = Encoding.UTF8.GetBytes(messageToSend);
await stream.WriteAsync(messageBytes, ct).ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(15), ct);
}
}
And the client side code [node.js]:
import { Socket } from 'net';
var client = new Socket();
client.on('connect', () => console.log("CONNECTED"));
client.on('data', data => console.log("data", data.toString()));
client.on('error', err => console.error(err));
client.connect(11111, "127.0.0.1");
printMessages();
async function printMessages() {
for (let i = 0; i < 10; i++) {
client.write('Ping ' + i);
await sleep(4000);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

Google apps script, forward all emails except one

I have a script that forwards all of my emails that come in during specific times to email#domain.com.
The problem I am having, is that sometimes email#domain.com sends me an email during that time.
Can anyone suggest a way to add a rule that it should forward to all addresses except forwarding address?
function forwardEmails() {
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var settings = ss.getSheetByName('Settings').getDataRange().getValues();
if (settings[1][1] == 'No')
return;
if (settings[2][1] == "")
throw new Error('Please set Forward Email!');
var email = PropertiesService.getScriptProperties().getProperty('email');
if (!email)
throw new Error('First authorize script by clicking on menu: Email Forwarder >> Authorize Script');
var today = (new Date());
var applicableRules = validRules(today);
if (applicableRules) {
var unread = GmailApp.getInboxUnreadCount();
if (!unread)
return;
var threads = GmailApp.getInboxThreads(0, unread>100?100:unread);
var cutOff = today.getTime() - (MINUTES*60*1000 + 100); // 10 mins + 100 ms
for (var i=0; i<threads.length; i++) {
var msgs = threads[i].getMessages();
for (var j=0; j<msgs.length; j++) {
var from = msgs[j].getFrom();
var msgDate = msgs[j].getDate();
var msgTime = (new Date(msgDate)).getTime();
var diff1 = msgTime - cutOff;
if (diff1 > 0 && from.indexOf(email) == -1) {
var to = msgs[j].getTo();
var subject = msgs[j].getSubject();
var attach = msgs[j].getAttachments();
var body = msgs[j].getBody();
var plainBody = msgs[j].getPlainBody();
var replyTo = msgs[j].getReplyTo();
var options = {replyTo: from};
if (attach.length > 0)
options.attachment = attach;
GmailApp.sendEmail(settings[2][1], subject, plainBody, options );
}
}
}
}
} catch (error) {
var html = '<p>'+ error + '</p><br><br>Email Forwarder Rules & Settings<p>Line: '+ error.lineNumber + ', Filename: ' + error.fileName + '</p>';
if (!email)
email = Session.getActiveUser().getEmail();
MailApp.sendEmail(email, 'Email Forwarder Script Failed!', error + '\n\nEmail Forwarder Rules & Settings URL: ' + ss.getUrl(), {htmlBody: html});
}
}
Instead of using getInboxThreads() use search().
getInboxThreads() will return threads in your inbox while search() will return those that meet the search query. The following query will include include messages in your inbox but exclude those from email#domain.com
in:inbox -from:email#domain.com
You could add a check in the second loop of the "forwardEmails" function. The code below would skip any unread emails which have arrived from the forwarding address (I'm assuming the forwarding email is referenced in "settings[2][1]".
for (var i=0; i<threads.length; i++) {
var msgs = threads[i].getMessages();
for (var j=0; j<msgs.length; j++) {
var from = msgs[j].getFrom();
var msgDate = msgs[j].getDate();
var msgTime = (new Date(msgDate)).getTime();
var diff1 = msgTime - cutOff;
// New code
if (from === settings[2][1]) {
continue;
}

Dart HTML Server. How do I have the server refuse more than one client connection?

I'm writing a web application that is to be used by only one client and want to accept only one connection to the server. The LAN will be confined to an aircraft. I'm really new to Dart, HTML etc. How can I refuse multiple connections to the server?
Here's my code fir the HTTP server -
class MicroServer {
var address;
var port;
var httpServer; // global
MicroServer(this.address, this.port) {
final HTTP_ROOT_PATH = Platform.script.resolve('../build/web').toFilePath();
final virDir = new VirtualDirectory(HTTP_ROOT_PATH)
..jailRoot = false
..allowDirectoryListing = true;
HttpServer.bind(address, port)
.then((httpserver) {
httpServer = httpserver;
httpserver.listen((request) {
virDir.serveRequest(request);
});
});
}
}
Dart is single-threaded, so you can safely use check a variable to see if there's a current connection:
bool hasClient = false;
HttpServer.bind(address, port)
.then((httpserver) {
httpServer = httpserver;
httpserver.listen((request) {
if (hasClient) {
sendBusyPage(request);
} else {
hasClient = true;
virDir.serveRequest(request);
hasClient = false;
}
});
});
}
I have found that the code below works so far. I could also have taken advantage of
if(request.session.isNew) // then grab the session.id etc.
but it's just as easy to use the session.id variable since I will use it anyway.
class MicroServer {
var address;
var port;
var httpServer;
var sessionID; // null until first request received
MicroServer(this.address, this.port) {
final HTTP_ROOT_PATH = Platform.script.resolve('../build/web').toFilePath();
final virDir = new VirtualDirectory(HTTP_ROOT_PATH)
..jailRoot = false // process links will work
..followLinks = true
..allowDirectoryListing = true;
HttpServer.bind(address, port)
.then((httpserver) {
httpServer = httpserver;
httpserver.idleTimeout = null;
print("micro server started on ${httpserver.address}:${httpserver.port}");
httpserver.listen((request) {
if(sessionID == null) {
sessionID = request.session.id;
virDir.serveRequest(request);
} else if(sessionID == request.session.id){
virDir.serveRequest(request);
} else {
request.response.writeln('ERROR - Connection is in use.');
request.response.close();
request.session.destroy();
}
});
}).catchError((e) => print(e.toString()));
}
}

Writing to sockets

I have trouble understanding the reason for the error I get when the user tries to write anything to the server:
TypeError: Object #<identifyClient> has no method 'write'
at writeToAll (/root/node/mud/server.js:13:15)
Why does identifyClient() complaints about the write(), while it happens in the writeToAll() (line 15 has comment next to it)? identifyClient() really only sets the name for the client, and should not be concerned what happens in the writeToAll().
var net = require("net");
var clients = [];
function identifyClient(client) {
this.name = null;
this.client = client;
}
function writeToAll(data, client) {
for (var i = 0; i < clients.length; i++) {
if (clients[i] != client) {
clients[i].write(data); // This is line 15
}
}
}
var server = net.createServer(function(client) {
var clientID = new identifyClient(client);
clients.push(clientID);
client.on("data", function(data) {
writeToAll(data, client);
});
});
server.listen(4444);
Replace clients[i] with clients[i].client
also you have to remove the client from the clients array once it disconnects.

jQuery/Ajax form success message

I have a couple of forms on a site I'm working on and the script that controls them doesn't include a success message, so when they're submitted the input data just disappears and the user doesn't know if it's been actually sent or not. I've looked around a bit for answers, but because this file controls an email submission form, a contact form, and a twitter feed, it's a bit much for me to see what's what.
Here's the code, I'd just like to let users know that their message has been sent for both the email input form and the contact form. I appreciate any help that's out there!
$(document).ready(function() {
//Set default hint if nothing is entered
setHints();
//Bind JavaScript event on SignUp Button
$('#signUp').click(function(){
signUp($('#subscribe').val());
});
//Bind JavaScript event on Send Message Button
$('#sendMessage').click(function(){
if(validateInput()){
sendMail();
}else
{
alert('Please fill all fields to send us message.');
}
});
//Load initial site state (countdown, twitts)
initialize();
});
var setHints = function()
{
$('#subscribe').attachHint('Enter your email to be notified when more info is available');
$('[name=contact_name]').attachHint('Name');
$('[name=contact_email]').attachHint('Email');
$('[name=contact_subject]').attachHint('Subject');
$('[name=contact_message]').attachHint('Message');
};
var signUp = function(inputEmail)
{
var isValid = true;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(inputEmail)){
isValid = false;
alert('Your email is not in valid format');
}
if(isValid){
var params = {
'action' : 'SingUp',
'email' : inputEmail
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('#subscribe').val('');
}
}
}
});
}
};
var initialize = function()
{
var params = {
'action' : 'Initialize'
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('ul.twitts').empty();
if(responseObj.ResponseData.Twitts){
$('a.followUsURL').attr('href','http://twitter.com/#!/'+responseObj.ResponseData.Twitts[0].Name);
$.each(responseObj.ResponseData.Twitts, function(index, twitt){
var twitterTemplate = '<li>'
+ '#{0}'
+ '{2}'
+ '<span class="time">{3}</span>'
+ '</li>';
$('ul.twitts').append(StringFormat(twitterTemplate, twitt.Name, twitt.StatusID, twitt.Text, twitt.Date));
});
}
if(responseObj.ResponseData.Start_Date)
{
setInterval(function(){
var countDownObj = calculateTimeDifference(responseObj.ResponseData.Start_Date);
if(countDownObj){
$('#days').text(countDownObj.Days);
$('#hours').text(countDownObj.Hours);
$('#minutes').text(countDownObj.Minutes);
$('#seconds').text(countDownObj.Seconds);
}
}, 1000);
}
}
}
}
});
};
var validateInput = function(){
var isValid = true;
$('input, textarea').each(function(){
if($(this).hasClass('required'))
{
if($(this).val()!=''){
if($(this).hasClass('email'))
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($(this).val())){
isValid = false;
alert('Your email is not in valid format');
}
}
}else
{
isValid = false;
}
}
});
return isValid;
};
var resetInput = function(){
$('input, textarea').each(function() {
$(this).val('').text('');
});
};
var sendMail = function(){
var params = {
'action' : 'SendMessage',
'name' : $('[name=contact_name]').val(),
'email' : $('[name=contact_email]').val(),
'subject' : $('[name=contact_subject]').val(),
'message' : $('[name=contact_message]').val()
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
$('label.sendingStatus').text(responseObj.ResponseData);
}
resetInput();
$('#sendMail').removeAttr('disabled');
},
error: function (xhr, ajaxOptions, thrownError){
//xhr.status : 404, 303, 501...
var error = null;
switch(xhr.status)
{
case "301":
error = "Redirection Error!";
break;
case "307":
error = "Error, temporary server redirection!";
break;
case "400":
error = "Bad request!";
break;
case "404":
error = "Page not found!";
break;
case "500":
error = "Server is currently unavailable!";
break;
default:
error ="Unespected error, please try again later.";
}
if(error){
$('label.sendingStatus').text(error);
}
}
});
};
var calculateTimeDifference = function(startDate) {
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var day = hour * 24;
var seconds = 0;
var minutes = 0;
var hours = 0;
var days = 0;
var currentDate = new Date();
startDate = new Date(startDate);
var timeCounter = startDate - currentDate;
if (isNaN(timeCounter))
{
return NaN;
}
else
{
days = Math.floor(timeCounter / day);
timeCounter = timeCounter % day;
hours = Math.floor(timeCounter / hour);
timeCounter = timeCounter % hour;
minutes = Math.floor(timeCounter / minute);
timeCounter = timeCounter % minute;
seconds = Math.floor(timeCounter / second);
}
var tDiffObj = {
"Days" : days,
"Hours" : hours,
"Minutes" : minutes,
"Seconds" : seconds
};
return tDiffObj;
};
var StringFormat = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var regExpression = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(regExpression, arguments[i + 1]);
}
return s;
}
You need to hook into the success callbacks of each of the $.ajax calls. You can create a method that will show a message for those:
For example, your signUp function's success callback could look like:
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('#subscribe').val('');
showMessage('Your subscription was received. Thank you!');
}
}
}
And you just create a method that will show the message to the user
var showMessage = function (msg) {
// of course, you wouldn't use alert,
// but would inject the message into the dom somewhere
alert(msg);
}
You would call showMessage anywhere the success callback was fired.
You can add your success notifing code in each of the $.ajax success handlers.