Tuesday, May 5, 2020

Xamarin.Android - Build Real-life Application Using TCP/IP - Part Two

In the last article, I had completed the first module of the client application. Let’s start to build a server application for workstations, in this one.

Server Application

 
Step 1
 
Let’s create a console app project with a .NET framework.
 
Xamarin.Android – Build Real Life Application-using TCP/IP  

Step 2

Create an instance of TcpClient and TcpListener inside your Program class by using appropriate namespaces. Also, declare a local variable type string with the name ipString.

  1. public static TcpClient client;  
  2. private static TcpListener listener;  
  3. private static string ipString;  

Step 3

Let’s write a method inside your Main function that will catch and return your machine's IP Address.

  1. IPAddress[] localIp = Dns.GetHostAddresses(Dns.GetHostName());  
  2.             foreach (IPAddress address in localIp)  
  3.             {  
  4.                 if (address.AddressFamily == AddressFamily.InterNetwork)  
  5.                 {  
  6.                     ipString = address.ToString();  
  7.                 }  
  8.             }  

Step 4

Now, in this step, we are ready to start listening. I am using 1234 as my port number and I will use the current machine's local IP address and my port number for endpoints. After following all these steps, now, we can accept any TCP client and connect with clients.

  1. IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipString), 1234);  
  2.             listener = new TcpListener(ep);  
  3.             listener.Start();  
  4.             Console.WriteLine(@"    
  5.             ===================================================    
  6.                    Started listening requests at: {0}:{1}    
  7.             ===================================================",  
  8.             ep.Address, ep.Port);  
  9.             client = listener.AcceptTcpClient();  
  10.             Console.WriteLine("Connected to client!" + " \n");  
Xamarin.Android – Build Real Life Application-using TCP/IP

Step 5

After connecting with the client, I will perform my first function that will sleep the workstations using the client command. While the client is connected with the Server, if a client will send the SLP2 command, then the server will execute the sleep function that I will write in the next step.

  1. while (client.Connected)  
  2.             {  
  3.                 try  
  4.                 {  
  5.                     const int bytesize = 1024 * 1024;  
  6.                     byte[] buffer = new byte[bytesize];  
  7.                     string x = client.GetStream().Read(buffer, 0, bytesize).ToString();  
  8.                     var data = ASCIIEncoding.ASCII.GetString(buffer);  
  9.   
  10.                     if (data.ToUpper().Contains("SLP2"))  
  11.                     {  
  12.                         Console.WriteLine("Pc is going to Sleep Mode!" + " \n");  
  13.                         Sleep();  
  14.                     }                      
  15.                 }  
  16.                 catch (Exception exc)  
  17.                 {  
  18.                     client.Dispose();  
  19.                     client.Close();  
  20.                 }  
  21.             }  

Step 6

First, add the following namespaces to your project; then write the sleep function inside your Main function.

  1. using System.Windows.Forms;  
  2.   
  3. void Sleep()  
  4.             {  
  5.                 Application.SetSuspendState(PowerState.Suspend, truetrue);  
  6.             }  

Client Application

Let’s turn back to your client application that we created in the last episode and start to write the client connecting with server functionality. In this module, we will build a connection with the server application.

Step 1 – Create Connection Class

We need to define a connection class in our project for creating a TCP Client instance. Create a new class with name Connection.cs and write the following code into it.

(FileName: Connection.cs)

  1. public class Connection  
  2.     {  
  3.         private static Connection _instance;  
  4.   
  5.         public static Connection Instance  
  6.         {  
  7.             get  
  8.             {  
  9.                 if (_instance == null) _instance = new Connection();  
  10.                 return _instance;  
  11.             }  
  12.         }  
  13.         public TcpClient client { get; set; }  
  14.     }  

Step 2 - Creating User Interface for Connection

We need two edit texts for IP address & port and one button for connecting with the server. Create a new layout with the name "connect" inside your layout folder that you will find in Resources folder. Replace the following code into it.

(File Name: Connect.axml , Folder Name: Layout)

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:padding="20dp">  
  7.     <TextView  
  8.         android:text="Connect to Server"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:gravity="center"  
  12.         android:id="@+id/textView1" />  
  13.     <EditText  
  14.         android:hint="IP Address"  
  15.         android:layout_width="match_parent"  
  16.         android:layout_height="wrap_content"  
  17.         android:id="@+id/edtIpAddress" />  
  18.     <EditText  
  19.         android:hint="Port"  
  20.         android:layout_width="match_parent"  
  21.         android:layout_height="wrap_content"  
  22.         android:id="@+id/edtPort" />  
  23.     <Button  
  24.         android:text="Connect"  
  25.         android:layout_width="match_parent"  
  26.         android:layout_height="wrap_content"  
  27.         android:id="@+id/btnConnect" />  
  28. </LinearLayout>  
Xamarin.Android – Build Real Life Application-using TCP/IP

Step 3 - Add Activity For Connect

In this activity, first, we will bind our UI controls with this activity. Then, we will connect with server application using workstation IP address and port. Write the following code in your connect activity.

 (FileName: Connect.cs)

  1. public class Connect : Activity  
  2. {  
  3.     private EditText edtIp, edtport;  
  4.     private Button btnConnect;  
  5.     private TcpClient client;  
  6.     protected override void OnCreate(Bundle savedInstanceState)  
  7.     {  
  8.         base.OnCreate(savedInstanceState);  
  9.         client = new TcpClient();  
  10.         // Create your application here  
  11.         SetContentView(Resource.Layout.Connect);  
  12.         edtIp = FindViewById<EditText>(Resource.Id.edtIpAddress);  
  13.         edtport = FindViewById<EditText>(Resource.Id.edtPort);  
  14.         btnConnect = FindViewById<Button>(Resource.Id.btnConnect);  
  15.         btnConnect.Click += async delegate   
  16.         {  
  17.             try  
  18.             {  
  19.                 await client.ConnectAsync(edtIp.Text, Convert.ToInt32(edtport.Text));  
  20.                 if (client.Connected)  
  21.                 {  
  22.                     Connection.Instance.client = client;  
  23.                     Toast.MakeText(this"Client connected to server!", ToastLength.Short).Show();  
  24.                     Intent intent = new Intent(thistypeof(Control));  
  25.                     StartActivity(intent);  
  26.                 }  
  27.                 else  
  28.                 {  
  29.                     Toast.MakeText(this"Connection feild!", ToastLength.Short).Show();  
  30.                 }  
  31.             }  
  32.             catch (Exception x)  
  33.             {  
  34.                 Toast.MakeText(this"Connection feild!", ToastLength.Short).Show();  
  35.                 Toast.MakeText(this"" + x, ToastLength.Short).Show();  
  36.             }  
  37.         };  
  38.     }  
  39. }  

We have completed our second module of client application that will hit the request to the server for building a connection. Then, we will be able to send any kind of commands to our server and also receive the response from the server.

Test Connection

Let’s test the connection of the server and client app that we have just built. However, the main launcher of Xamarin.Android application will display the sign-in page. You can sign In only if you already have registered otherwise you cannot navigate to the next page. Therefore, first, register yourself and then sign in using your credentials. Start your server application and copy the IP address & port of workstation from the server app. Put this required parameter into client application and hit Connect.
 
Xamarin.Android – Build Real Life Application-using TCP/IP  

Step 1 - Creating User Interface for Control

Now, I am going to my next module. Add a new layout by going to Solution Explorer-> Project Name-> Resources-> Layout. Right-click to add a new item, select Layout, and give it a name, such as Control.axml. Open this layout file and add the following code.

(Folder Name: Layout , File Name: Control.axml)

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:padding="20dp">  
  7.       
  8.     <Button  
  9.         android:text="Sleep"  
  10.         android:layout_width="match_parent"  
  11.         android:layout_height="wrap_content"  
  12.         android:id="@+id/btnSleep" />  
  13.       
  14. </LinearLayout>  

Step 2 - Add Activity for Control

Add a new activity with the name Control.cs and replace the following code.

  1. public class Control : Activity  
  2.     {  
  3.         private Button btnSleep;  
  4.           
  5.         NetworkStream stream;  
  6.         protected override void OnCreate(Bundle savedInstanceState)  
  7.         {  
  8.             base.OnCreate(savedInstanceState);  
  9.             var client = Connection.Instance.client;  
  10.             // Create your application here  
  11.             SetContentView(Resource.Layout.Control);  
  12.             btnSleep = FindViewById<Button>(Resource.Id.btnSleep);  
  13.               
  14.             btnSleep.Click += delegate   
  15.             {  
  16.                 stream = client.GetStream();  
  17.                 String s = "SLP2";  
  18.                 byte[] message = Encoding.ASCII.GetBytes(s);  
  19.                 stream.Write(message, 0, message.Length);  
  20.             };              
  21.         }          
  22.     }  
Xamarin.Android – Build Real Life Application-using TCP/IP

Connect with the server and press the Sleep button. Your workstation will go to sleep mode. In the next part, I will complete all my project functionality. So, please stay tuned for my next article of this series.

Ahsan Siddique

Author & Editor

Experienced Microsoft Certified Azure Developer and Trainer with a demonstrated history of working in the computer software industry. Skilled in .NET, .NET Core, C#, Xamarin, Azure, Kubernetes, Docker Containers, Microservices, CI/CD, and Universal Windows Platform with Strong engineering professional.

1 Comments:

  1. titanium dog teeth implants - Titanium Art
    Titanium Art titanium band ring is proud to introduce a new product columbia titanium jacket for TITanium art. titanium wedding bands for men Titanium Art is revlon hair dryer brush titanium the first product from the TitiArt used ford edge titanium line.

    ReplyDelete