Sockets: delay between receive and send (WriteStream.WriteAsync() and ReadStream.ReadAsync())












0















How do you Correctly implement a delay between sending a string using WriteStream.WriteAsync() and waiting for a response using ReadStream.ReadAsync()?



I am using the rda.SocketsForPCL plugin to create the TCP client socket and thereafter the respective read and write streams.



When I implement a delay using TimeSpan.FromMilliseconds(200)), I get an System.NullReferenceException: Object reference not set to an instance of an object in VS 2017. I am new to C# and Xamarin and I am not sure how to implement a delay other than the above method that will not cause an exception to be thrown.



Is there a "Global" exception handler that can be somehow implemented to deal with exceptions such as these as VS 2017 does not break the code and show you exactly where the exception has actually occurred?



I have implemented the below activity Page in Xamarin.Forms but it is not allowing me to implement a delay using the TimeSpan.FromMilliseconds(200)); which is commented in the UpdateUserDataAsync() function below:



 public InputPage ()
{
try
{
InitializeComponent();
}
catch (Exception ex)
{
string err = ex.Message;
throw;
}

client = SharedSocket.Instance().getSocket(); // Get persistent Socket ===> client connection
UpdateUserDataAsync(); // Used to update the contents of the Listview
loadSampleData(); // Load the Items in the ListView

BindingContext = this;

this.BindingContext = new Relays(); // Binding the Listview items
var neg = lstView.BindingContext as Relays;
InputID = neg.ID;
}

private async void UpdateUserDataAsync() // Request and Receive Controller Name
{
byte rv = new byte { 0x01, 0x01, 0x01 0x01, 0x01, 0x01, 0x01 }; // Request
Send_CntrP(rv); // Send request
//await Task.Delay(TimeSpan.FromMilliseconds(200));
rec2 = await ReceiveByte();
}// UpdateUserDataAsync

private void loadSampleData()
{
ObservableCollection<Relays> lisInputs = new ObservableCollection<Relays>();

if (rec2.Length >= 4)
{
byte states = Encoding.ASCII.GetBytes(rec2); // Create byte array of received string

for (int j=6; j<22; j++)
{
switch (states[j])
{
case 0x00:
lisInputs.Add(new Relays { ID = j - 5, Name = "ERROR" + (j - 5), State = "ERROR" });
break;

case 0x01:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State= "Toggle"});
break;

case 0x02:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "ON"});
break;

case 0x03:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "OFF"});
break;

case 0x04:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "NO"});
break;

case 0x05:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "NC"});
break;

case 0x10:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "SC"});
break;

case 0x11:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "OC"});
break;
}
}
}
else
{
for (int i = 0; i < num; i++)
{
Images[i] = "round_off.png";
InputName[i] = "ERROR";
InputOn[i] = false;
InputState[i] = "ERROR";

lisInputs.Add(new Relays { Name = InputName[i] + i, ImageUrl = Images[i], ID = i, State = InputState[i] });
}
}

lstView.ItemsSource = lisInputs;
}

public class MyListItemEventArgs : EventArgs
{
public Relays MyItem { get; set; }

public MyListItemEventArgs(Relays item)
{
this.MyItem = item;
}
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++ Sending Messages+++++++++ +++++++++++++++++++++++
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public async void Send_CntrP(byte Comms)
{
var Len = Comms.Length; // Read the byte array Length

if (client.Socket.Connected && Len <= 23) // No longer than 22 bytes of data to be sent
{
try
{
await client.WriteStream.WriteAsync(Comms, 0, Len); // Send data of specified Length
await client.WriteStream.FlushAsync(); // Make sure all the buffer output data is sent
await Task.Delay(TimeSpan.FromMilliseconds(200)); // Delay before next TX to ensure buffer is emptied correctly
}
catch (Exception ex) // Exception Handler
{
return;
throw ex;
}
}// Client Connected

else
{
XFToast.ShortMessage("Error updating name.nrPlease check the connection or length of the entry"); //Android Native Toast Message
}
}// Send_CntrP
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++++++++++++++++++++++++++++++ Receiving Messages +++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public async Task<string> ReceiveByte() // Receive messages Asynchronously
{
int bytesRec = 0;
var buffer = new byte[28];

if (client.Socket.Connected) // Check Socket connection
{
while (bytesRec != -1) // Read received data ---> byte-by-byte
{
try
{
bytesRec = await client.ReadStream.ReadAsync(buffer, 0, 28);
}

catch (Exception ex) // Exception Handler (to prevent App crash)
{
XFToast.ShortMessage("Error receiving message.nrPlease check the WIFI connection.");
return "ERROR"; // Return an "ERROR" message if failed
throw ex;
}

var meh = buffer.ToArray();
rec2 = System.Text.Encoding.UTF8.GetString(meh);

if (rec2.Length >= 1 && rec2.Length < 30)
{
return await Task.FromResult(rec2); // Return a string
}
else
{
//await DisplayAlert("Error", "Error receiving message.", "OK");
XFToast.ShortMessage("Error receiving message.nrPlease verify the connection."); //Android Native Toast Message
return "ERROR"; // Return an "ERROR" message
}
}// Reading response
}// Client
else
{
return err; // Return a "Connection Error" string when no connection is available
}

return rec2; // Return the received bytes in a string
}// ReceiveByte
//
++++++++++++++++++++++++++++++++++++++++++++++++
}


I am sorry for the long post but I have been struggling with this problem for a while now and I am not experienced enough to deal with all the async methods and exception "finding" and then the handling thereof with VS 2017 and Xamarin as I am still learning the basics :(



Thank you in advance for any help/suggestions.










share|improve this question

























  • I usually put the read and write code into the same lock so only one can occur at a time. Then you never do both a read and write at the same time and you are always waiting for the write to complete before reading.

    – jdweng
    Nov 14 '18 at 11:08











  • @jdweng, how would I put them in the same lock (or block) as you mention?

    – Ryno
    Nov 14 '18 at 11:13
















0















How do you Correctly implement a delay between sending a string using WriteStream.WriteAsync() and waiting for a response using ReadStream.ReadAsync()?



I am using the rda.SocketsForPCL plugin to create the TCP client socket and thereafter the respective read and write streams.



When I implement a delay using TimeSpan.FromMilliseconds(200)), I get an System.NullReferenceException: Object reference not set to an instance of an object in VS 2017. I am new to C# and Xamarin and I am not sure how to implement a delay other than the above method that will not cause an exception to be thrown.



Is there a "Global" exception handler that can be somehow implemented to deal with exceptions such as these as VS 2017 does not break the code and show you exactly where the exception has actually occurred?



I have implemented the below activity Page in Xamarin.Forms but it is not allowing me to implement a delay using the TimeSpan.FromMilliseconds(200)); which is commented in the UpdateUserDataAsync() function below:



 public InputPage ()
{
try
{
InitializeComponent();
}
catch (Exception ex)
{
string err = ex.Message;
throw;
}

client = SharedSocket.Instance().getSocket(); // Get persistent Socket ===> client connection
UpdateUserDataAsync(); // Used to update the contents of the Listview
loadSampleData(); // Load the Items in the ListView

BindingContext = this;

this.BindingContext = new Relays(); // Binding the Listview items
var neg = lstView.BindingContext as Relays;
InputID = neg.ID;
}

private async void UpdateUserDataAsync() // Request and Receive Controller Name
{
byte rv = new byte { 0x01, 0x01, 0x01 0x01, 0x01, 0x01, 0x01 }; // Request
Send_CntrP(rv); // Send request
//await Task.Delay(TimeSpan.FromMilliseconds(200));
rec2 = await ReceiveByte();
}// UpdateUserDataAsync

private void loadSampleData()
{
ObservableCollection<Relays> lisInputs = new ObservableCollection<Relays>();

if (rec2.Length >= 4)
{
byte states = Encoding.ASCII.GetBytes(rec2); // Create byte array of received string

for (int j=6; j<22; j++)
{
switch (states[j])
{
case 0x00:
lisInputs.Add(new Relays { ID = j - 5, Name = "ERROR" + (j - 5), State = "ERROR" });
break;

case 0x01:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State= "Toggle"});
break;

case 0x02:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "ON"});
break;

case 0x03:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "OFF"});
break;

case 0x04:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "NO"});
break;

case 0x05:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "NC"});
break;

case 0x10:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "SC"});
break;

case 0x11:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "OC"});
break;
}
}
}
else
{
for (int i = 0; i < num; i++)
{
Images[i] = "round_off.png";
InputName[i] = "ERROR";
InputOn[i] = false;
InputState[i] = "ERROR";

lisInputs.Add(new Relays { Name = InputName[i] + i, ImageUrl = Images[i], ID = i, State = InputState[i] });
}
}

lstView.ItemsSource = lisInputs;
}

public class MyListItemEventArgs : EventArgs
{
public Relays MyItem { get; set; }

public MyListItemEventArgs(Relays item)
{
this.MyItem = item;
}
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++ Sending Messages+++++++++ +++++++++++++++++++++++
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public async void Send_CntrP(byte Comms)
{
var Len = Comms.Length; // Read the byte array Length

if (client.Socket.Connected && Len <= 23) // No longer than 22 bytes of data to be sent
{
try
{
await client.WriteStream.WriteAsync(Comms, 0, Len); // Send data of specified Length
await client.WriteStream.FlushAsync(); // Make sure all the buffer output data is sent
await Task.Delay(TimeSpan.FromMilliseconds(200)); // Delay before next TX to ensure buffer is emptied correctly
}
catch (Exception ex) // Exception Handler
{
return;
throw ex;
}
}// Client Connected

else
{
XFToast.ShortMessage("Error updating name.nrPlease check the connection or length of the entry"); //Android Native Toast Message
}
}// Send_CntrP
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++++++++++++++++++++++++++++++ Receiving Messages +++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public async Task<string> ReceiveByte() // Receive messages Asynchronously
{
int bytesRec = 0;
var buffer = new byte[28];

if (client.Socket.Connected) // Check Socket connection
{
while (bytesRec != -1) // Read received data ---> byte-by-byte
{
try
{
bytesRec = await client.ReadStream.ReadAsync(buffer, 0, 28);
}

catch (Exception ex) // Exception Handler (to prevent App crash)
{
XFToast.ShortMessage("Error receiving message.nrPlease check the WIFI connection.");
return "ERROR"; // Return an "ERROR" message if failed
throw ex;
}

var meh = buffer.ToArray();
rec2 = System.Text.Encoding.UTF8.GetString(meh);

if (rec2.Length >= 1 && rec2.Length < 30)
{
return await Task.FromResult(rec2); // Return a string
}
else
{
//await DisplayAlert("Error", "Error receiving message.", "OK");
XFToast.ShortMessage("Error receiving message.nrPlease verify the connection."); //Android Native Toast Message
return "ERROR"; // Return an "ERROR" message
}
}// Reading response
}// Client
else
{
return err; // Return a "Connection Error" string when no connection is available
}

return rec2; // Return the received bytes in a string
}// ReceiveByte
//
++++++++++++++++++++++++++++++++++++++++++++++++
}


I am sorry for the long post but I have been struggling with this problem for a while now and I am not experienced enough to deal with all the async methods and exception "finding" and then the handling thereof with VS 2017 and Xamarin as I am still learning the basics :(



Thank you in advance for any help/suggestions.










share|improve this question

























  • I usually put the read and write code into the same lock so only one can occur at a time. Then you never do both a read and write at the same time and you are always waiting for the write to complete before reading.

    – jdweng
    Nov 14 '18 at 11:08











  • @jdweng, how would I put them in the same lock (or block) as you mention?

    – Ryno
    Nov 14 '18 at 11:13














0












0








0








How do you Correctly implement a delay between sending a string using WriteStream.WriteAsync() and waiting for a response using ReadStream.ReadAsync()?



I am using the rda.SocketsForPCL plugin to create the TCP client socket and thereafter the respective read and write streams.



When I implement a delay using TimeSpan.FromMilliseconds(200)), I get an System.NullReferenceException: Object reference not set to an instance of an object in VS 2017. I am new to C# and Xamarin and I am not sure how to implement a delay other than the above method that will not cause an exception to be thrown.



Is there a "Global" exception handler that can be somehow implemented to deal with exceptions such as these as VS 2017 does not break the code and show you exactly where the exception has actually occurred?



I have implemented the below activity Page in Xamarin.Forms but it is not allowing me to implement a delay using the TimeSpan.FromMilliseconds(200)); which is commented in the UpdateUserDataAsync() function below:



 public InputPage ()
{
try
{
InitializeComponent();
}
catch (Exception ex)
{
string err = ex.Message;
throw;
}

client = SharedSocket.Instance().getSocket(); // Get persistent Socket ===> client connection
UpdateUserDataAsync(); // Used to update the contents of the Listview
loadSampleData(); // Load the Items in the ListView

BindingContext = this;

this.BindingContext = new Relays(); // Binding the Listview items
var neg = lstView.BindingContext as Relays;
InputID = neg.ID;
}

private async void UpdateUserDataAsync() // Request and Receive Controller Name
{
byte rv = new byte { 0x01, 0x01, 0x01 0x01, 0x01, 0x01, 0x01 }; // Request
Send_CntrP(rv); // Send request
//await Task.Delay(TimeSpan.FromMilliseconds(200));
rec2 = await ReceiveByte();
}// UpdateUserDataAsync

private void loadSampleData()
{
ObservableCollection<Relays> lisInputs = new ObservableCollection<Relays>();

if (rec2.Length >= 4)
{
byte states = Encoding.ASCII.GetBytes(rec2); // Create byte array of received string

for (int j=6; j<22; j++)
{
switch (states[j])
{
case 0x00:
lisInputs.Add(new Relays { ID = j - 5, Name = "ERROR" + (j - 5), State = "ERROR" });
break;

case 0x01:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State= "Toggle"});
break;

case 0x02:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "ON"});
break;

case 0x03:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "OFF"});
break;

case 0x04:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "NO"});
break;

case 0x05:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "NC"});
break;

case 0x10:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "SC"});
break;

case 0x11:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "OC"});
break;
}
}
}
else
{
for (int i = 0; i < num; i++)
{
Images[i] = "round_off.png";
InputName[i] = "ERROR";
InputOn[i] = false;
InputState[i] = "ERROR";

lisInputs.Add(new Relays { Name = InputName[i] + i, ImageUrl = Images[i], ID = i, State = InputState[i] });
}
}

lstView.ItemsSource = lisInputs;
}

public class MyListItemEventArgs : EventArgs
{
public Relays MyItem { get; set; }

public MyListItemEventArgs(Relays item)
{
this.MyItem = item;
}
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++ Sending Messages+++++++++ +++++++++++++++++++++++
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public async void Send_CntrP(byte Comms)
{
var Len = Comms.Length; // Read the byte array Length

if (client.Socket.Connected && Len <= 23) // No longer than 22 bytes of data to be sent
{
try
{
await client.WriteStream.WriteAsync(Comms, 0, Len); // Send data of specified Length
await client.WriteStream.FlushAsync(); // Make sure all the buffer output data is sent
await Task.Delay(TimeSpan.FromMilliseconds(200)); // Delay before next TX to ensure buffer is emptied correctly
}
catch (Exception ex) // Exception Handler
{
return;
throw ex;
}
}// Client Connected

else
{
XFToast.ShortMessage("Error updating name.nrPlease check the connection or length of the entry"); //Android Native Toast Message
}
}// Send_CntrP
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++++++++++++++++++++++++++++++ Receiving Messages +++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public async Task<string> ReceiveByte() // Receive messages Asynchronously
{
int bytesRec = 0;
var buffer = new byte[28];

if (client.Socket.Connected) // Check Socket connection
{
while (bytesRec != -1) // Read received data ---> byte-by-byte
{
try
{
bytesRec = await client.ReadStream.ReadAsync(buffer, 0, 28);
}

catch (Exception ex) // Exception Handler (to prevent App crash)
{
XFToast.ShortMessage("Error receiving message.nrPlease check the WIFI connection.");
return "ERROR"; // Return an "ERROR" message if failed
throw ex;
}

var meh = buffer.ToArray();
rec2 = System.Text.Encoding.UTF8.GetString(meh);

if (rec2.Length >= 1 && rec2.Length < 30)
{
return await Task.FromResult(rec2); // Return a string
}
else
{
//await DisplayAlert("Error", "Error receiving message.", "OK");
XFToast.ShortMessage("Error receiving message.nrPlease verify the connection."); //Android Native Toast Message
return "ERROR"; // Return an "ERROR" message
}
}// Reading response
}// Client
else
{
return err; // Return a "Connection Error" string when no connection is available
}

return rec2; // Return the received bytes in a string
}// ReceiveByte
//
++++++++++++++++++++++++++++++++++++++++++++++++
}


I am sorry for the long post but I have been struggling with this problem for a while now and I am not experienced enough to deal with all the async methods and exception "finding" and then the handling thereof with VS 2017 and Xamarin as I am still learning the basics :(



Thank you in advance for any help/suggestions.










share|improve this question
















How do you Correctly implement a delay between sending a string using WriteStream.WriteAsync() and waiting for a response using ReadStream.ReadAsync()?



I am using the rda.SocketsForPCL plugin to create the TCP client socket and thereafter the respective read and write streams.



When I implement a delay using TimeSpan.FromMilliseconds(200)), I get an System.NullReferenceException: Object reference not set to an instance of an object in VS 2017. I am new to C# and Xamarin and I am not sure how to implement a delay other than the above method that will not cause an exception to be thrown.



Is there a "Global" exception handler that can be somehow implemented to deal with exceptions such as these as VS 2017 does not break the code and show you exactly where the exception has actually occurred?



I have implemented the below activity Page in Xamarin.Forms but it is not allowing me to implement a delay using the TimeSpan.FromMilliseconds(200)); which is commented in the UpdateUserDataAsync() function below:



 public InputPage ()
{
try
{
InitializeComponent();
}
catch (Exception ex)
{
string err = ex.Message;
throw;
}

client = SharedSocket.Instance().getSocket(); // Get persistent Socket ===> client connection
UpdateUserDataAsync(); // Used to update the contents of the Listview
loadSampleData(); // Load the Items in the ListView

BindingContext = this;

this.BindingContext = new Relays(); // Binding the Listview items
var neg = lstView.BindingContext as Relays;
InputID = neg.ID;
}

private async void UpdateUserDataAsync() // Request and Receive Controller Name
{
byte rv = new byte { 0x01, 0x01, 0x01 0x01, 0x01, 0x01, 0x01 }; // Request
Send_CntrP(rv); // Send request
//await Task.Delay(TimeSpan.FromMilliseconds(200));
rec2 = await ReceiveByte();
}// UpdateUserDataAsync

private void loadSampleData()
{
ObservableCollection<Relays> lisInputs = new ObservableCollection<Relays>();

if (rec2.Length >= 4)
{
byte states = Encoding.ASCII.GetBytes(rec2); // Create byte array of received string

for (int j=6; j<22; j++)
{
switch (states[j])
{
case 0x00:
lisInputs.Add(new Relays { ID = j - 5, Name = "ERROR" + (j - 5), State = "ERROR" });
break;

case 0x01:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State= "Toggle"});
break;

case 0x02:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "ON"});
break;

case 0x03:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "OFF"});
break;

case 0x04:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "NO"});
break;

case 0x05:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "NC"});
break;

case 0x10:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "SC"});
break;

case 0x11:
lisInputs.Add(new Relays { ID = j - 5, Name = "IOK" + (j - 5), ImageUrl = "round_on.png", State = "OC"});
break;
}
}
}
else
{
for (int i = 0; i < num; i++)
{
Images[i] = "round_off.png";
InputName[i] = "ERROR";
InputOn[i] = false;
InputState[i] = "ERROR";

lisInputs.Add(new Relays { Name = InputName[i] + i, ImageUrl = Images[i], ID = i, State = InputState[i] });
}
}

lstView.ItemsSource = lisInputs;
}

public class MyListItemEventArgs : EventArgs
{
public Relays MyItem { get; set; }

public MyListItemEventArgs(Relays item)
{
this.MyItem = item;
}
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++ Sending Messages+++++++++ +++++++++++++++++++++++
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public async void Send_CntrP(byte Comms)
{
var Len = Comms.Length; // Read the byte array Length

if (client.Socket.Connected && Len <= 23) // No longer than 22 bytes of data to be sent
{
try
{
await client.WriteStream.WriteAsync(Comms, 0, Len); // Send data of specified Length
await client.WriteStream.FlushAsync(); // Make sure all the buffer output data is sent
await Task.Delay(TimeSpan.FromMilliseconds(200)); // Delay before next TX to ensure buffer is emptied correctly
}
catch (Exception ex) // Exception Handler
{
return;
throw ex;
}
}// Client Connected

else
{
XFToast.ShortMessage("Error updating name.nrPlease check the connection or length of the entry"); //Android Native Toast Message
}
}// Send_CntrP
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++++++++++++++++++++++++++++++ Receiving Messages +++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public async Task<string> ReceiveByte() // Receive messages Asynchronously
{
int bytesRec = 0;
var buffer = new byte[28];

if (client.Socket.Connected) // Check Socket connection
{
while (bytesRec != -1) // Read received data ---> byte-by-byte
{
try
{
bytesRec = await client.ReadStream.ReadAsync(buffer, 0, 28);
}

catch (Exception ex) // Exception Handler (to prevent App crash)
{
XFToast.ShortMessage("Error receiving message.nrPlease check the WIFI connection.");
return "ERROR"; // Return an "ERROR" message if failed
throw ex;
}

var meh = buffer.ToArray();
rec2 = System.Text.Encoding.UTF8.GetString(meh);

if (rec2.Length >= 1 && rec2.Length < 30)
{
return await Task.FromResult(rec2); // Return a string
}
else
{
//await DisplayAlert("Error", "Error receiving message.", "OK");
XFToast.ShortMessage("Error receiving message.nrPlease verify the connection."); //Android Native Toast Message
return "ERROR"; // Return an "ERROR" message
}
}// Reading response
}// Client
else
{
return err; // Return a "Connection Error" string when no connection is available
}

return rec2; // Return the received bytes in a string
}// ReceiveByte
//
++++++++++++++++++++++++++++++++++++++++++++++++
}


I am sorry for the long post but I have been struggling with this problem for a while now and I am not experienced enough to deal with all the async methods and exception "finding" and then the handling thereof with VS 2017 and Xamarin as I am still learning the basics :(



Thank you in advance for any help/suggestions.







c# sockets xamarin xamarin.forms exception-handling






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 11:09







Ryno

















asked Nov 14 '18 at 10:51









RynoRyno

379




379













  • I usually put the read and write code into the same lock so only one can occur at a time. Then you never do both a read and write at the same time and you are always waiting for the write to complete before reading.

    – jdweng
    Nov 14 '18 at 11:08











  • @jdweng, how would I put them in the same lock (or block) as you mention?

    – Ryno
    Nov 14 '18 at 11:13



















  • I usually put the read and write code into the same lock so only one can occur at a time. Then you never do both a read and write at the same time and you are always waiting for the write to complete before reading.

    – jdweng
    Nov 14 '18 at 11:08











  • @jdweng, how would I put them in the same lock (or block) as you mention?

    – Ryno
    Nov 14 '18 at 11:13

















I usually put the read and write code into the same lock so only one can occur at a time. Then you never do both a read and write at the same time and you are always waiting for the write to complete before reading.

– jdweng
Nov 14 '18 at 11:08





I usually put the read and write code into the same lock so only one can occur at a time. Then you never do both a read and write at the same time and you are always waiting for the write to complete before reading.

– jdweng
Nov 14 '18 at 11:08













@jdweng, how would I put them in the same lock (or block) as you mention?

– Ryno
Nov 14 '18 at 11:13





@jdweng, how would I put them in the same lock (or block) as you mention?

– Ryno
Nov 14 '18 at 11:13












1 Answer
1






active

oldest

votes


















1














Here is sample code of my solution



    enum READ_WRITE
{
READ,
WRITE
}
public class Test
{
private static readonly object readWritelock = new object();
public static object ReadWrite(READ_WRITE readWrite, object data)
{
object returnValue = 0;
lock (readWritelock)
{
switch (readWrite)
{
case READ_WRITE.READ :
//add you read code here
break;

case READ_WRITE.WRITE :
//add your write code here
break;
}
}
return returnValue;
}
}





share|improve this answer


























  • Thank you, I will go try and implement this in my code.

    – Ryno
    Nov 14 '18 at 11:19











  • I am still not able to implement a delay between sending and receiving; when I send and call the receive, it reads a bunch of zeros. Could this be because it is trying to read the received message too fast?

    – Ryno
    Nov 14 '18 at 13:57











  • I don't know enough about xamarin to give an answer, but do know database architecture very well. You basically have a database and the question is the database designed to handle shared transactions. A shared database contains locking methods that make sure you do not have conflicts. If you have a database with 10 items and one customer buys 9 items at the same time another customer want 5 items. What does the 2nd customer get?A database that is designed for sharing the second customer get 1 item. A database the is not designed for sharing gives the 2nd customer 5 items (4 do not exist).

    – jdweng
    Nov 14 '18 at 14:16











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53298460%2fsockets-delay-between-receive-and-send-writestream-writeasync-and-readstream%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














Here is sample code of my solution



    enum READ_WRITE
{
READ,
WRITE
}
public class Test
{
private static readonly object readWritelock = new object();
public static object ReadWrite(READ_WRITE readWrite, object data)
{
object returnValue = 0;
lock (readWritelock)
{
switch (readWrite)
{
case READ_WRITE.READ :
//add you read code here
break;

case READ_WRITE.WRITE :
//add your write code here
break;
}
}
return returnValue;
}
}





share|improve this answer


























  • Thank you, I will go try and implement this in my code.

    – Ryno
    Nov 14 '18 at 11:19











  • I am still not able to implement a delay between sending and receiving; when I send and call the receive, it reads a bunch of zeros. Could this be because it is trying to read the received message too fast?

    – Ryno
    Nov 14 '18 at 13:57











  • I don't know enough about xamarin to give an answer, but do know database architecture very well. You basically have a database and the question is the database designed to handle shared transactions. A shared database contains locking methods that make sure you do not have conflicts. If you have a database with 10 items and one customer buys 9 items at the same time another customer want 5 items. What does the 2nd customer get?A database that is designed for sharing the second customer get 1 item. A database the is not designed for sharing gives the 2nd customer 5 items (4 do not exist).

    – jdweng
    Nov 14 '18 at 14:16
















1














Here is sample code of my solution



    enum READ_WRITE
{
READ,
WRITE
}
public class Test
{
private static readonly object readWritelock = new object();
public static object ReadWrite(READ_WRITE readWrite, object data)
{
object returnValue = 0;
lock (readWritelock)
{
switch (readWrite)
{
case READ_WRITE.READ :
//add you read code here
break;

case READ_WRITE.WRITE :
//add your write code here
break;
}
}
return returnValue;
}
}





share|improve this answer


























  • Thank you, I will go try and implement this in my code.

    – Ryno
    Nov 14 '18 at 11:19











  • I am still not able to implement a delay between sending and receiving; when I send and call the receive, it reads a bunch of zeros. Could this be because it is trying to read the received message too fast?

    – Ryno
    Nov 14 '18 at 13:57











  • I don't know enough about xamarin to give an answer, but do know database architecture very well. You basically have a database and the question is the database designed to handle shared transactions. A shared database contains locking methods that make sure you do not have conflicts. If you have a database with 10 items and one customer buys 9 items at the same time another customer want 5 items. What does the 2nd customer get?A database that is designed for sharing the second customer get 1 item. A database the is not designed for sharing gives the 2nd customer 5 items (4 do not exist).

    – jdweng
    Nov 14 '18 at 14:16














1












1








1







Here is sample code of my solution



    enum READ_WRITE
{
READ,
WRITE
}
public class Test
{
private static readonly object readWritelock = new object();
public static object ReadWrite(READ_WRITE readWrite, object data)
{
object returnValue = 0;
lock (readWritelock)
{
switch (readWrite)
{
case READ_WRITE.READ :
//add you read code here
break;

case READ_WRITE.WRITE :
//add your write code here
break;
}
}
return returnValue;
}
}





share|improve this answer















Here is sample code of my solution



    enum READ_WRITE
{
READ,
WRITE
}
public class Test
{
private static readonly object readWritelock = new object();
public static object ReadWrite(READ_WRITE readWrite, object data)
{
object returnValue = 0;
lock (readWritelock)
{
switch (readWrite)
{
case READ_WRITE.READ :
//add you read code here
break;

case READ_WRITE.WRITE :
//add your write code here
break;
}
}
return returnValue;
}
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 14 '18 at 11:19

























answered Nov 14 '18 at 11:17









jdwengjdweng

17.2k2717




17.2k2717













  • Thank you, I will go try and implement this in my code.

    – Ryno
    Nov 14 '18 at 11:19











  • I am still not able to implement a delay between sending and receiving; when I send and call the receive, it reads a bunch of zeros. Could this be because it is trying to read the received message too fast?

    – Ryno
    Nov 14 '18 at 13:57











  • I don't know enough about xamarin to give an answer, but do know database architecture very well. You basically have a database and the question is the database designed to handle shared transactions. A shared database contains locking methods that make sure you do not have conflicts. If you have a database with 10 items and one customer buys 9 items at the same time another customer want 5 items. What does the 2nd customer get?A database that is designed for sharing the second customer get 1 item. A database the is not designed for sharing gives the 2nd customer 5 items (4 do not exist).

    – jdweng
    Nov 14 '18 at 14:16



















  • Thank you, I will go try and implement this in my code.

    – Ryno
    Nov 14 '18 at 11:19











  • I am still not able to implement a delay between sending and receiving; when I send and call the receive, it reads a bunch of zeros. Could this be because it is trying to read the received message too fast?

    – Ryno
    Nov 14 '18 at 13:57











  • I don't know enough about xamarin to give an answer, but do know database architecture very well. You basically have a database and the question is the database designed to handle shared transactions. A shared database contains locking methods that make sure you do not have conflicts. If you have a database with 10 items and one customer buys 9 items at the same time another customer want 5 items. What does the 2nd customer get?A database that is designed for sharing the second customer get 1 item. A database the is not designed for sharing gives the 2nd customer 5 items (4 do not exist).

    – jdweng
    Nov 14 '18 at 14:16

















Thank you, I will go try and implement this in my code.

– Ryno
Nov 14 '18 at 11:19





Thank you, I will go try and implement this in my code.

– Ryno
Nov 14 '18 at 11:19













I am still not able to implement a delay between sending and receiving; when I send and call the receive, it reads a bunch of zeros. Could this be because it is trying to read the received message too fast?

– Ryno
Nov 14 '18 at 13:57





I am still not able to implement a delay between sending and receiving; when I send and call the receive, it reads a bunch of zeros. Could this be because it is trying to read the received message too fast?

– Ryno
Nov 14 '18 at 13:57













I don't know enough about xamarin to give an answer, but do know database architecture very well. You basically have a database and the question is the database designed to handle shared transactions. A shared database contains locking methods that make sure you do not have conflicts. If you have a database with 10 items and one customer buys 9 items at the same time another customer want 5 items. What does the 2nd customer get?A database that is designed for sharing the second customer get 1 item. A database the is not designed for sharing gives the 2nd customer 5 items (4 do not exist).

– jdweng
Nov 14 '18 at 14:16





I don't know enough about xamarin to give an answer, but do know database architecture very well. You basically have a database and the question is the database designed to handle shared transactions. A shared database contains locking methods that make sure you do not have conflicts. If you have a database with 10 items and one customer buys 9 items at the same time another customer want 5 items. What does the 2nd customer get?A database that is designed for sharing the second customer get 1 item. A database the is not designed for sharing gives the 2nd customer 5 items (4 do not exist).

– jdweng
Nov 14 '18 at 14:16


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53298460%2fsockets-delay-between-receive-and-send-writestream-writeasync-and-readstream%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

List item for chat from Array inside array React Native

Thiostrepton

Caerphilly