Socket connections between Android and external device using Xamarin











up vote
0
down vote

favorite












I'm trying to establish a socket connection between my Android smartphone and an external custom device by using the Xamarin framework. This external device is supposed to accept some custom commands and return a response. This works fine with a Telnet client such as Tera Term. However, I didn't have any luck with my Xamarin code so far. It looks as follows:



using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace MyNamespace
{
public partial class MainPage : ContentPage
{
private Socket mySocket;

public MainPage()
{
InitializeComponent();
}

private bool ConnectToSocketAndReturnConnectionStatus(Socket socket, IPEndPoint remoteEndPoint)
{
try
{
socket.Connect(remoteEndPoint);
}
catch (Exception e)
{
Debug.WriteLine("Exception: Network subsystem is down", e);
}

return socket.Connected;
}

private void AcceptCallback(IAsyncResult ar)
{
// Receive from socket
byte buffer = new byte[1024];
int iRx = mySocket.Receive(buffer);
char chars = new char[iRx];

Decoder d = Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
String recv = new String(chars);
DisplayAlert("Message from Socket", recv, "OK");
}

private void SendMyCommand()
{
byte byData = Encoding.ASCII.GetBytes("DataStringOfMyCommand");
mySocket.Send(byData);
DisplayAlert("Message from Socket", "My command sent", "OK");
}

void ConnectButtonClicked(object sender, EventArgs args)
{
// Init socket
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAdd = IPAddress.Parse("x.x.x.x");
IPEndPoint remoteEndPoint = new IPEndPoint(ipAdd,myPortNumber);

bool mySocketIsConnected = ConnectToSocketAndReturnConnectionStatus(mySocket, remoteEndPoint);

if (mySocketIsConnected) {
DisplayAlert("Message from Socket", "Connection successfully established", "OK");
try
{
mySocket.Blocking = false;
mySocket.Listen(100);
mySocket.BeginAccept(new AsyncCallback(AcceptCallback), mySocket);
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
}
else { DisplayAlert("Message from Socket", "No connection possible. Check your network!", "OK"); }
}

void MyCommandButtonClicked(object sender, EventArgs args)
{
SendMyCommand();
}
}
}


The alert message "Connection successfully established" pops up as expected. Thus, I suppose that the external device is at least found. However, I'm not able to see the response as no alert pop-up is displayed once I send my custom command. Apparently, the function "AcceptCallback(...)" is never called. What am I doing wrong here?



Your help is very much appreciated.



P.S: Here is the corresponding .xaml file, just in case you are wondering how the UI looks like:



<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyNamespace"
x:Class="MyNamespace.MainPage"
Title="My Tool">

<StackLayout>
<Label x:Name="label"
Text="Welcome"
FontSize="Medium"
VerticalOptions="CenterAndExpand"
HorizontalOptions="Center" />

<Button Text="Connect to hardware"
VerticalOptions="CenterAndExpand"
HorizontalOptions="Center"
Clicked="ConnectButtonClicked" />

<Button Text="Send my command"
VerticalOptions="CenterAndExpand"
HorizontalOptions="Center"
Clicked="MyCommandButtonClicked" />

</StackLayout>

</ContentPage>









share|improve this question


























    up vote
    0
    down vote

    favorite












    I'm trying to establish a socket connection between my Android smartphone and an external custom device by using the Xamarin framework. This external device is supposed to accept some custom commands and return a response. This works fine with a Telnet client such as Tera Term. However, I didn't have any luck with my Xamarin code so far. It looks as follows:



    using Microsoft.AspNetCore.Http;
    using System;
    using System.Diagnostics;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Net.WebSockets;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Xamarin.Forms;

    namespace MyNamespace
    {
    public partial class MainPage : ContentPage
    {
    private Socket mySocket;

    public MainPage()
    {
    InitializeComponent();
    }

    private bool ConnectToSocketAndReturnConnectionStatus(Socket socket, IPEndPoint remoteEndPoint)
    {
    try
    {
    socket.Connect(remoteEndPoint);
    }
    catch (Exception e)
    {
    Debug.WriteLine("Exception: Network subsystem is down", e);
    }

    return socket.Connected;
    }

    private void AcceptCallback(IAsyncResult ar)
    {
    // Receive from socket
    byte buffer = new byte[1024];
    int iRx = mySocket.Receive(buffer);
    char chars = new char[iRx];

    Decoder d = Encoding.UTF8.GetDecoder();
    int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
    String recv = new String(chars);
    DisplayAlert("Message from Socket", recv, "OK");
    }

    private void SendMyCommand()
    {
    byte byData = Encoding.ASCII.GetBytes("DataStringOfMyCommand");
    mySocket.Send(byData);
    DisplayAlert("Message from Socket", "My command sent", "OK");
    }

    void ConnectButtonClicked(object sender, EventArgs args)
    {
    // Init socket
    mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IPAddress ipAdd = IPAddress.Parse("x.x.x.x");
    IPEndPoint remoteEndPoint = new IPEndPoint(ipAdd,myPortNumber);

    bool mySocketIsConnected = ConnectToSocketAndReturnConnectionStatus(mySocket, remoteEndPoint);

    if (mySocketIsConnected) {
    DisplayAlert("Message from Socket", "Connection successfully established", "OK");
    try
    {
    mySocket.Blocking = false;
    mySocket.Listen(100);
    mySocket.BeginAccept(new AsyncCallback(AcceptCallback), mySocket);
    }
    catch (Exception e)
    {
    Debug.WriteLine(e.ToString());
    }
    }
    else { DisplayAlert("Message from Socket", "No connection possible. Check your network!", "OK"); }
    }

    void MyCommandButtonClicked(object sender, EventArgs args)
    {
    SendMyCommand();
    }
    }
    }


    The alert message "Connection successfully established" pops up as expected. Thus, I suppose that the external device is at least found. However, I'm not able to see the response as no alert pop-up is displayed once I send my custom command. Apparently, the function "AcceptCallback(...)" is never called. What am I doing wrong here?



    Your help is very much appreciated.



    P.S: Here is the corresponding .xaml file, just in case you are wondering how the UI looks like:



    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:MyNamespace"
    x:Class="MyNamespace.MainPage"
    Title="My Tool">

    <StackLayout>
    <Label x:Name="label"
    Text="Welcome"
    FontSize="Medium"
    VerticalOptions="CenterAndExpand"
    HorizontalOptions="Center" />

    <Button Text="Connect to hardware"
    VerticalOptions="CenterAndExpand"
    HorizontalOptions="Center"
    Clicked="ConnectButtonClicked" />

    <Button Text="Send my command"
    VerticalOptions="CenterAndExpand"
    HorizontalOptions="Center"
    Clicked="MyCommandButtonClicked" />

    </StackLayout>

    </ContentPage>









    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I'm trying to establish a socket connection between my Android smartphone and an external custom device by using the Xamarin framework. This external device is supposed to accept some custom commands and return a response. This works fine with a Telnet client such as Tera Term. However, I didn't have any luck with my Xamarin code so far. It looks as follows:



      using Microsoft.AspNetCore.Http;
      using System;
      using System.Diagnostics;
      using System.Linq;
      using System.Net;
      using System.Net.Sockets;
      using System.Net.WebSockets;
      using System.Text;
      using System.Threading;
      using System.Threading.Tasks;
      using Xamarin.Forms;

      namespace MyNamespace
      {
      public partial class MainPage : ContentPage
      {
      private Socket mySocket;

      public MainPage()
      {
      InitializeComponent();
      }

      private bool ConnectToSocketAndReturnConnectionStatus(Socket socket, IPEndPoint remoteEndPoint)
      {
      try
      {
      socket.Connect(remoteEndPoint);
      }
      catch (Exception e)
      {
      Debug.WriteLine("Exception: Network subsystem is down", e);
      }

      return socket.Connected;
      }

      private void AcceptCallback(IAsyncResult ar)
      {
      // Receive from socket
      byte buffer = new byte[1024];
      int iRx = mySocket.Receive(buffer);
      char chars = new char[iRx];

      Decoder d = Encoding.UTF8.GetDecoder();
      int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
      String recv = new String(chars);
      DisplayAlert("Message from Socket", recv, "OK");
      }

      private void SendMyCommand()
      {
      byte byData = Encoding.ASCII.GetBytes("DataStringOfMyCommand");
      mySocket.Send(byData);
      DisplayAlert("Message from Socket", "My command sent", "OK");
      }

      void ConnectButtonClicked(object sender, EventArgs args)
      {
      // Init socket
      mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      IPAddress ipAdd = IPAddress.Parse("x.x.x.x");
      IPEndPoint remoteEndPoint = new IPEndPoint(ipAdd,myPortNumber);

      bool mySocketIsConnected = ConnectToSocketAndReturnConnectionStatus(mySocket, remoteEndPoint);

      if (mySocketIsConnected) {
      DisplayAlert("Message from Socket", "Connection successfully established", "OK");
      try
      {
      mySocket.Blocking = false;
      mySocket.Listen(100);
      mySocket.BeginAccept(new AsyncCallback(AcceptCallback), mySocket);
      }
      catch (Exception e)
      {
      Debug.WriteLine(e.ToString());
      }
      }
      else { DisplayAlert("Message from Socket", "No connection possible. Check your network!", "OK"); }
      }

      void MyCommandButtonClicked(object sender, EventArgs args)
      {
      SendMyCommand();
      }
      }
      }


      The alert message "Connection successfully established" pops up as expected. Thus, I suppose that the external device is at least found. However, I'm not able to see the response as no alert pop-up is displayed once I send my custom command. Apparently, the function "AcceptCallback(...)" is never called. What am I doing wrong here?



      Your help is very much appreciated.



      P.S: Here is the corresponding .xaml file, just in case you are wondering how the UI looks like:



      <?xml version="1.0" encoding="utf-8" ?>
      <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
      xmlns:local="clr-namespace:MyNamespace"
      x:Class="MyNamespace.MainPage"
      Title="My Tool">

      <StackLayout>
      <Label x:Name="label"
      Text="Welcome"
      FontSize="Medium"
      VerticalOptions="CenterAndExpand"
      HorizontalOptions="Center" />

      <Button Text="Connect to hardware"
      VerticalOptions="CenterAndExpand"
      HorizontalOptions="Center"
      Clicked="ConnectButtonClicked" />

      <Button Text="Send my command"
      VerticalOptions="CenterAndExpand"
      HorizontalOptions="Center"
      Clicked="MyCommandButtonClicked" />

      </StackLayout>

      </ContentPage>









      share|improve this question













      I'm trying to establish a socket connection between my Android smartphone and an external custom device by using the Xamarin framework. This external device is supposed to accept some custom commands and return a response. This works fine with a Telnet client such as Tera Term. However, I didn't have any luck with my Xamarin code so far. It looks as follows:



      using Microsoft.AspNetCore.Http;
      using System;
      using System.Diagnostics;
      using System.Linq;
      using System.Net;
      using System.Net.Sockets;
      using System.Net.WebSockets;
      using System.Text;
      using System.Threading;
      using System.Threading.Tasks;
      using Xamarin.Forms;

      namespace MyNamespace
      {
      public partial class MainPage : ContentPage
      {
      private Socket mySocket;

      public MainPage()
      {
      InitializeComponent();
      }

      private bool ConnectToSocketAndReturnConnectionStatus(Socket socket, IPEndPoint remoteEndPoint)
      {
      try
      {
      socket.Connect(remoteEndPoint);
      }
      catch (Exception e)
      {
      Debug.WriteLine("Exception: Network subsystem is down", e);
      }

      return socket.Connected;
      }

      private void AcceptCallback(IAsyncResult ar)
      {
      // Receive from socket
      byte buffer = new byte[1024];
      int iRx = mySocket.Receive(buffer);
      char chars = new char[iRx];

      Decoder d = Encoding.UTF8.GetDecoder();
      int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
      String recv = new String(chars);
      DisplayAlert("Message from Socket", recv, "OK");
      }

      private void SendMyCommand()
      {
      byte byData = Encoding.ASCII.GetBytes("DataStringOfMyCommand");
      mySocket.Send(byData);
      DisplayAlert("Message from Socket", "My command sent", "OK");
      }

      void ConnectButtonClicked(object sender, EventArgs args)
      {
      // Init socket
      mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      IPAddress ipAdd = IPAddress.Parse("x.x.x.x");
      IPEndPoint remoteEndPoint = new IPEndPoint(ipAdd,myPortNumber);

      bool mySocketIsConnected = ConnectToSocketAndReturnConnectionStatus(mySocket, remoteEndPoint);

      if (mySocketIsConnected) {
      DisplayAlert("Message from Socket", "Connection successfully established", "OK");
      try
      {
      mySocket.Blocking = false;
      mySocket.Listen(100);
      mySocket.BeginAccept(new AsyncCallback(AcceptCallback), mySocket);
      }
      catch (Exception e)
      {
      Debug.WriteLine(e.ToString());
      }
      }
      else { DisplayAlert("Message from Socket", "No connection possible. Check your network!", "OK"); }
      }

      void MyCommandButtonClicked(object sender, EventArgs args)
      {
      SendMyCommand();
      }
      }
      }


      The alert message "Connection successfully established" pops up as expected. Thus, I suppose that the external device is at least found. However, I'm not able to see the response as no alert pop-up is displayed once I send my custom command. Apparently, the function "AcceptCallback(...)" is never called. What am I doing wrong here?



      Your help is very much appreciated.



      P.S: Here is the corresponding .xaml file, just in case you are wondering how the UI looks like:



      <?xml version="1.0" encoding="utf-8" ?>
      <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
      xmlns:local="clr-namespace:MyNamespace"
      x:Class="MyNamespace.MainPage"
      Title="My Tool">

      <StackLayout>
      <Label x:Name="label"
      Text="Welcome"
      FontSize="Medium"
      VerticalOptions="CenterAndExpand"
      HorizontalOptions="Center" />

      <Button Text="Connect to hardware"
      VerticalOptions="CenterAndExpand"
      HorizontalOptions="Center"
      Clicked="ConnectButtonClicked" />

      <Button Text="Send my command"
      VerticalOptions="CenterAndExpand"
      HorizontalOptions="Center"
      Clicked="MyCommandButtonClicked" />

      </StackLayout>

      </ContentPage>






      android sockets xamarin xamarin.forms xamarin.android






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 7 at 11:14









      Hagbard

      102111




      102111





























          active

          oldest

          votes











          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',
          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%2f53188381%2fsocket-connections-between-android-and-external-device-using-xamarin%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53188381%2fsocket-connections-between-android-and-external-device-using-xamarin%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







          這個網誌中的熱門文章

          Tangent Lines Diagram Along Smooth Curve

          Yusuf al-Mu'taman ibn Hud

          Zucchini