In the netframework v2, the socket use the Invoke (BeginRead) method to call a method (example ReceiveMsg) as below:
client = new TcpClient();
client.Connect(SERVERIP, PORTNO);
data = new byte[client.ReceiveBufferSize];
SendMessage("hello\n");
client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(client.ReceiveBufferSize), ReceiveMsg, null);
Will this method ReceiveMsg of socket always be in "Auto Mode" such that it will standby to receive the message broadcast by SocketServer?
or It is using System.Threading.Thread.Sleep() to make ReceiveMsg method always active so that it will be in ready mode to respond to when SocketServer broadcast message?
How to do this in Netframework v4 or 4.5 socket for this ReceiveMsg method as BeginRead() is no longer required.
Thanks.
Below is the code for socket in netframework v4 :http://msdn.microsoft.com/en-us/library/hh202858(v=vs.92).aspx (for WP mango/ Wp8)
Client.Connect();
Client.Send();
Client.Receive();
public string Receive()
{
//-- receive the reply from server
string response = "Receiving Operation Timeout";
// We are receiving over an established socket connection
if (_socket != null)
{
// Create SocketAsyncEventArgs context object
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
// Setup the buffer to receive the data
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
// Inline event handler for the Completed event.
// Note: This even handler was implemented inline in order to make this method self-contained.
socketEventArg.Completed += new EventHandler(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// Retrieve the data from the buffer
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response = response.Trim('\0');
}
else
{
response = e.SocketError.ToString();
}
_clientDone.Set();
});
// Sets the state of the event to nonsignaled, causing threads to block
_clientDone.Reset();
// Make an asynchronous Receive request over the socket
_socket.ReceiveAsync(socketEventArg);
// Block the UI thread for a maximum of TIMEOUT_MILLISECONDS seconds.
// If no response comes back within this time then proceed
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "Socket is not initialized";
}
return response;
}
Related
I am using flutter as a client-side and using the firebase extension to get the checkout URL for payment purposes.
This is working fine but I want to save the webhook response data on my MySQL db. The stripe webhook sends data on each event and I want to store each event response on my DB by which I will filter the data from there.
I am using node js as the backend but I don't have much knowledge of nodejs.
I followed the stripe nodejs documentation from which I am triggering the events
and this is the documentation code -
// server.js
//
// Use this sample code to handle webhook events in your integration.
//
// 1) Paste this code into a new file (server.js)
//
// 2) Install dependencies
// npm install stripe
// npm install express
//
// 3) Run the server on http://localhost:4242
// node server.js
const stripe = require('stripe');
const express = require('express');
const app = express();
// This is your Stripe CLI webhook secret for testing your endpoint locally.
const endpointSecret = "whsec_a86c898114804f99965ae4a14a7a93731a4c0bdffa506fa3d24d73ac89dd56f3";
app.post('/webhook', express.raw({type: 'application/json'}), (request, response) => {
const sig = request.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
} catch (err) {
response.status(400).send(`Webhook Error: ${err.message}`);
return;
}
// Handle the event
switch (event.type) {
case 'checkout.session.async_payment_failed':
const session = event.data.object;
// Then define and call a function to handle the event checkout.session.async_payment_failed
break;
case 'checkout.session.async_payment_succeeded':
const session = event.data.object;
// Then define and call a function to handle the event checkout.session.async_payment_succeeded
break;
case 'payment_intent.created':
const paymentIntent = event.data.object;
// Then define and call a function to handle the event payment_intent.created
break;
case 'payment_intent.processing':
const paymentIntent = event.data.object;
// Then define and call a function to handle the event payment_intent.processing
break;
// ... handle other event types
default:
console.log(`Unhandled event type ${event.type}`);
}
// Return a 200 response to acknowledge receipt of the event
response.send();
});
app.listen(4242, () => console.log('Running on port 4242'));
now, how can I connect MySQL on each switch case and save the data on my mysql db.
(note - I dont have pior knowledge of nodejs and mysql I have just read the documentation and following everything)
I'm trying to get some custom columns values (longitude,latitude) from ASPNetUsers Table from the DB , When I send a Get request throw browser I get a 200 ok with the requested json .. but when I try to use GetStringAsync to deserialize the response in my xamarin app I don't get any response .
In AccountController class
// POST api/Account/GetUserPostion
[Route("GetUserPostion")]
public LocationDataToPostAsync GetUserPostion()
{
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var manager = new ApplicationUserManager(store);
LocationDataToPostAsync locationData = new LocationDataToPostAsync();
var model = manager.FindById(User.Identity.GetUserId());
locationData.UserId = User.Identity.GetUserId();
if (model.Longitude != null) locationData.Longitude = (double) model.Longitude;
if (model.Latitude != null) locationData.Latitude = (double) model.Latitude;
return locationData;
}
In ApiService class in xamarin forms app
public async Task<LocationDataToPostAsync> GetUserLocationAsync(string accessToken)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var json = await client.GetStringAsync("http://10.0.2.2:45455/api/Account/GetUserPostion");
var location = JsonConvert.DeserializeObject<LocationDataToPostAsync>(json);
return location;
}
It is unclear from your code if the Task is awaited or you are calling .Result or .GetAwaiter().GetResult() on the Task. However, as we found out in the comments adding .ConfigureAwait(false) fixed your issue.
This indicates that the code cannot return to the context it came from, so adding .ConfigureAwait(false) the code doesn't return to the context.
In your case the context is probably the UI thread and when it tries to return the UI thread is blocked.
The most likely scenario why the UI Thread is block is because you called your Task in a wrong manner. If you call it with .Result on the UI thread you are synchronously blocking the UI thread, hence anything that tries to return to the UI thread, will deadlock, since you are blocking that.
The easy fix here is to just add .ConfigureAwait(false) in your code. The better solution would be not to block the UI thread by awaiting the Task.
I'm trying to implement progress bar on a website.
The Problem:
ProgressEvent.load is always the same as ProgressEvent.Total which prevent the progress to show the real state of the upload. At the first second the xhr request does sent it looks like it finished but actually the server is still getting parts of the file.
JS:
My js code(the part of the progress) looks like that:
xhr.upload.onprogress = function (event) {
var progress = Math.round(event.lengthComputable ? event.loaded * 100 / event.total : 0);
that._onProgressItem(item, progress);
};
the property lengthComputable is true.
the event.loaded is 4354707 as the event.total which is 4354707.
C# Server Side:
public async Task<FileResultViewModel> Upload(string type)
{
string ServerUploadFoler = "...";
// Verify that this is an HTML Form file upload request
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
// Create a stream provider for setting up output streams
var streamProvider = new MultipartFormDataStreamProvider(ServerUploadFolder);
// Read the MIME multipart asynchronously content using the stream provider we just created.
await Request.Content.ReadAsMultipartAsync(streamProvider);
string guid = String.Empty;
if (serverUploadMoveFolder != ServerUploadFolder)
{
foreach (MultipartFileData fileData in streamProvider.FileData)
{
guid = Guid.NewGuid().ToString();
string newFileName = serverUploadMoveFolder + guid + GetExtension(uploadType);
FileInfo fi = new FileInfo(fileData.LocalFileName);
fi.MoveTo(newFileName);
}
}
// Create response
return new FileResultViewModel
{
FileName = guid
};
}
Chrome debug after 1 second of upload with a file of 4.2MB:
In fiddler after the request has completed:
My questions are:
How does the browser knows the loaded size? How does it split the file to parts and based on what params?
How do the xhr.upload.onprogress function event get updated with the progress? Does it the server which report about his progress and if it is so where is it on the code because I didn't handle it.
Why doesn't the loaded property show the real size of part?
I have Http server loading data from different server (through HttpClient). You can see the code here: Dart HTTP server and Futures
I am able to load response to JSON map and now I want to keep this map in memory until it's invalidated (I can get information on change way faster that whole set). What would be best way to save my JSON map to in memory object and retrieve it from memory until it needs to be refreshed?
Solved in comments above. Summary: if you need to keep value in very simple "cache" scenario, you can make a copy of the object and invalidate it by copying new values over.
main() {
Map cachedMap = new Map();
var lastCached = new DateTime.now();
final Duration cacheDuration = new Duration(minutes: 10);
HttpServer.bind(InternetAddress.ANY_IP_V4, 4040).then((HttpServer server) {
print('listening on localhost, port ${server.port}');
server.listen((HttpRequest request) {
var now = new DateTime.now();
if (lastCached.add(cacheDuration).isAfter(now) && cachedMap.isNotEmpty) {
handleMap(request, cachedMap);
} else {
//do something to fill map
}
;
});
}).catchError((e) => print(e.toString()));
}
I am implementing of server-sent event(HTML5) in my project without using node.js, It is just simple webpage(another JSP page) call and i get response from it. But when i get response from it but none of method/function(onopen,onmessage or onerror) is execute...
Client Code:
if (!!window.EventSource) {
var source=new EventSource("kitAvailCall.jsp");
source.onopen = function(){
alert("Kit is not available");
source.close();
};
source.onmessage=function(event){
console.log(event.data);
alert("Kit is not available");
}
source.onerror =function(){
console.log("EventSOurce: Getting error call");
alert("Kit is not available");
}
}
Server-side code:
try{
while(true) {
Thread.sleep(15000);
String IpAddress = (String) session.getAttribute("IPName");
boolean bool;
if(IpAddress != null && ((new Date()).getTime() - session.getLastAccessedTime())/1000 > 28){
bool = sample.pingToKit((String) session.getAttribute("IPName"));
System.out.println("Long polling request: "+bool);
//if bool is false then i want to quit loop and back to browser
if(bool == false){
response.setHeader("Content-Type","text/event-stream");
response.setHeader("Cache-Control", "no-cache");
out.print("data: " + bool);
out.flush();
break;
}
}
}
}catch(Exception e){
System.out.println("Going bad CONN:"+ e);
}
I don't know much of java, but i could conjecture that you might be listening to the same controller/jsp servlet(whatever routes data in java) which you made to send as streaming.
Listen on a page other than kitavailcall.jsp. This script is meant only for streaming, use another view/html page other than kitavailcall.jsp
The thing you have to understand is, SSE is a concurrent process, you create another page and run on that page with the javascript(client code) included in that page. And your server should support multi-threading as well.