When does MessageWebSocket receive data? - events

Info: Despite using the WebSocket tag, I am using MessageWebSocket in my code because I am coding on UWP.
MessageWebSocket has an event called MessageReceived. I added an TypedEventHandler to this event when initializing the MessageWebSocket:
messageWebSocket.MessageReceived += new TypedEventHandler<MessageWebSocket, MessageWebSocketMessageReceivedEventArgs>(OnMessageRecieved);
After sending data with a method called SendData(), I expected that the MessageReceived event is fired. But it won't and I don't know why.
This is my SendData() method:
private async void SendData(DataWriter dataWriter)
{
try
{
_evaLogger.Info("Trying to send data...");
IBuffer buffer = dataWriter.DetachBuffer();
await messageWebSocket.OutputStream.WriteAsync(buffer);
_evaLogger.Info("Data was sent");
}
catch (Exception e)
{
_evaLogger.Error(e.Message, e);
}
}
If not after sending data, when does MessageWebSocket receive data?

I was able to figure out what the problem was. The server was expecting to get a text, instead I send data to the server. This is how the solution for sending text looks like:
private async Task SendData(DataWriter dataWriter)
{
try
{
_evaLogger.Info("Trying to send data...");
await dataWriter.StoreAsync();
_evaLogger.Info("Data was sent");
}
catch (Exception e)
{
_evaLogger.Error(e.Message, e);
}
}
It's also important to set the the MessageType to Utf8:
messageWebsocket.Control.MessageType = SocketMessageType.Utf8;

Related

Create server TCP in Winodws Univeral App (Javascript) and client Android

I want create a tcp server in c# and use it in universal app javascript based project, and I create the folowing code (Server):
//C# Windows Runtime Component
public sealed class Server
{
public Server()
{
Debug.WriteLine("Server...");
}
public async void Connection()
{
IPAddress ip = IPAddress.Parse("192.168.0.10");
TcpListener server = new TcpListener(ip, portNumber);
TcpClient client = default(TcpClient);
try
{
server.Start();
Debug.WriteLine("Server started ... " + ip.ToString());
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
while (true)
{
client = await server.AcceptTcpClientAsync();
byte[] recievedBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(recievedBuffer, 0, recievedBuffer.Length);
string msg = Encoding.UTF8.GetString(recievedBuffer, 0, recievedBuffer.Length);
Debug.WriteLine(msg);
}
}
}
//in HTML
<script>
console.log("test");
var server = new Server.Server();
server.connection();
console.log("msg");
</script>
I don't know why Debug.WriteLine and console.log method don't work, nothing are printed in output or in javascript console.
The Server code works with Android client, if the server is "Console App" project but in "Universal App Javscript" nothing append, I don't have warning or error.
So I don't know if I'm doing bad, because console.log and Debug.WriteLine don't work.
I have a solution that work with windows universal app, I remove Connection and add followings methods:
public async void StartServer()
{
try
{
var streamSocketListener = new Windows.Networking.Sockets.StreamSocketListener();
streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;
await streamSocketListener.BindEndpointAsync(new HostName("192.168.0.10"), PortNumber);
}
catch (Exception ex){}
}
private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
{
string request;
using (var streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
{
request = await streamReader.ReadLineAsync();
}
sender.Dispose();
}
//in main.js just call this method
new Server.Server().startServer();
But I still don't know why Debug.WriteLine() in c# and console.log() in javascript don't work.

Await call to web service is stopping the execution flow of the program

I have the following code:
public async Task IntiateDataFetchingProcess(string[] args)
{
try
{
ProcessArgs(args);
Log.Information("Run Mode: {RunModeID}", RunModeID);
switch (RunModeID)
{
case RunModeType.A:
await MethodAAsync();
break;
case RunModeType.B:
await MethodBAsync();
break;
case RunModeType.C:
TestMethod();
break;
default:
break;
}
}
catch (Exception ex)
{
throw;
}
}
private async Task MethodBAsync()
{
Console.WriteLine(DateTime.Now.ToLongTimeString());
// Call to webservice to get the data
var response = await _service.GetDataAsync(input1, request);
Console.WriteLine(DateTime.Now.ToLongTimeString());
}
On debugging I found that the execution call comes to the below line (of method: MethodBAsync) and stops there.
var response = await _service.GetDataAsync(input1, request);
Can anyone help me to know is there anything that I am missing here.
Ah, your code is getting deadlocked!
You just need to add .ConfigureAwait(false); to each line that you are awaiting.
Example:
var response = await _service.GetDataAsync(input1, request);
becomes
var response = await _service.GetDataAsync(input1,
request).ConfigureAwait(false);
For more information on .ConfigureAwait(), Stephen Cleary wrote an awesome post on it.

OData Connection in Xamarin Form

My code crashes and gives the following error on simulator. It attempts to run the try block in the GetDataFromOdataService() method and throws an error and also issue an alert. I am using Xamarin.Form
using Simple.OData.Client;
using System.Threading.Tasks;
private ODataClient mODataClient;
protected async override void OnAppearing ()
{
base.OnAppearing ();
await InitializeDataService ();
await GetDataFromOdataService();
}
public async Task <bool> InitializeDataService(){
try {
mODataClient = new ODataClient ("http://services.odata.org/Northwind/Northwind.svc/");
}
catch {
await DisplayAlert("Error", "Connection Error", "OK", "Cancel");
System.Diagnostics.Debug.WriteLine("ERROR!");
}
return true;
}
public async Task<bool> GetDataFromOdataService (){
try {
myCustomers= await mODataClient.For("Customers").Top(10).FindEntriesAsync();
}
catch {
await DisplayAlert("Error", "Connection Error", "OK", "Cancel");
System.Diagnostics.Debug.WriteLine("ERROR!");
}
return true;
}
Couple issues:-
In the constructor it was doing var list = new ListView() which constrained it locally than setting the class level scope variable. This was therefore adjusted to list = new ListView().
The other thing, was in the GetTheData function where the items source was being assigned as list.ItemsSource = myList; where it needed changing to list.ItemsSource = Customers;.
I've repackaged the zip file up and sent to you. Let me know if this works for you? You should now be able to see all your customers in the ListView.

Breaking on exception: String expected

When I run my code I get:
Breaking on exception: String expected
What I am trying to do is connect to my server using a websocket. However, it seems that no matter if my server is online or not the client still crashes.
My code:
import 'dart:html';
WebSocket serverConn;
int connectionAttempts;
TextAreaElement inputField = querySelector("#inputField");
String key;
void submitMessage(Event e) {
if (serverConn.readyState == WebSocket.OPEN) {
querySelector("#chatLog").text = inputField.value;
inputField.value = "";
}
}
void recreateConnection(Event e) {
connectionAttempts++;
if (connectionAttempts <= 5) {
inputField.value = "Connection failed, reconnecting. Attempt" + connectionAttempts.toString() + "out of 5";
serverConn = new WebSocket("ws://127.0.0.1:8887");
serverConn.onClose.listen(recreateConnection);
serverConn.onError.listen(recreateConnection);
} else {
inputField.value = "Connections ran out, please refresh site";
}
}
void connected(Event e) {
serverConn.sendString(key);
if (serverConn.readyState == WebSocket.OPEN) {
inputField.value = "CONNECTED!";
inputField.readOnly = false;
}
}
void main() {
serverConn = new WebSocket("ws://127.0.0.1:8887");
serverConn.onClose.listen(recreateConnection);
serverConn.onError.listen(recreateConnection);
serverConn.onOpen.listen(connected);
//querySelector("#inputField").onInput.listen(submitMessage);
querySelector("#sendInput").onClick.listen(submitMessage);
}
My Dart Editor says nothing about where the problem comes from nor does it give any warning until run-time.
You need to initialize int connectionAttempts; with a valid value;
connectionAttempts++; fails with an exception on null.
You also need an onMessage handler to receive messages.
serverConn.onMessage.listen((MessageEvent e) {
recreateConnection should register an onOpen handler as well.
After serverConn = new WebSocket the listener registered in main() will not work
If you register a listener where only one single event is expected you can use first instead of listen
serverConn.onOpen.first.then(connected);
According to #JAre s comment.
Try to use a hardcoded string
querySelector("#chatLog").text = 'someValue';
to ensure this is not the culprit.

Double download with WebClient.OpenReadAsync

Ok, in my app I need to download two lists of datas to elaborate them but I can't realize how to do it..
I click a button and then I think the downloads start almost together. This is good for me, what it's not good is that my application can't understand how to wait the downloads before doing anything else..
I know there's a design problem but I cannot figure out how to resolve it..
The code is something (more or less) like this:
private void button_Click(object sender, RoutedEventArgs e)
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://myRESTservice");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(uri); //this will set a private variableA
dwnl();
doSomething(); //this will do something with A and B
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dwnl()
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://myRESTservice/anotherAddress");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted_B);
webClient.OpenReadAsync(uri); //this will set a private variableB
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Hope you understand the problem..
While your application is downloading the data, i.e. the OpenReadAsync method has been called you could show a busy indication. Your doSomething method would then be called from within your OpenReadCompleted event handler.
If you want one download to occur after the other has completed then you could also call the dwnl method from within your OpenReadCompleted event handler.

Resources