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 .NET framework.
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.
- public static TcpClient client;
- private static TcpListener listener;
- 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.
- IPAddress[] localIp = Dns.GetHostAddresses(Dns.GetHostName());
- foreach (IPAddress address in localIp)
- {
- if (address.AddressFamily == AddressFamily.InterNetwork)
- {
- ipString = address.ToString();
- }
- }
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.
- IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipString), 1234);
- listener = new TcpListener(ep);
- listener.Start();
- Console.WriteLine(@"
- ===================================================
- Started listening requests at: {0}:{1}
- ===================================================",
- ep.Address, ep.Port);
- client = listener.AcceptTcpClient();
- Console.WriteLine("Connected to client!" + " \n");
Step 5
After connecting with the client, I will perform my first function that will sleep the workstations using client command. While the client is connected with the Server, if a client will send SLP2 command, then the server will execute the sleep function that I will write in the next step.
- while (client.Connected)
- {
- try
- {
- const int bytesize = 1024 * 1024;
- byte[] buffer = new byte[bytesize];
- string x = client.GetStream().Read(buffer, 0, bytesize).ToString();
- var data = ASCIIEncoding.ASCII.GetString(buffer);
-
- if (data.ToUpper().Contains("SLP2"))
- {
- Console.WriteLine("Pc is going to Sleep Mode!" + " \n");
- Sleep();
- }
- }
- catch (Exception exc)
- {
- client.Dispose();
- client.Close();
- }
- }
Step 6
First, add the following namespaces to your project; then write the sleep function inside your Main function.
- using System.Windows.Forms;
-
- void Sleep()
- {
- Application.SetSuspendState(PowerState.Suspend, true, true);
- }
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)
- public class Connection
- {
- private static Connection _instance;
-
- public static Connection Instance
- {
- get
- {
- if (_instance == null) _instance = new Connection();
- return _instance;
- }
- }
- public TcpClient client { get; set; }
- }
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)
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:padding="20dp">
- <TextView
- android:text="Connect to Server"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:id="@+id/textView1" />
- <EditText
- android:hint="IP Address"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/edtIpAddress" />
- <EditText
- android:hint="Port"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/edtPort" />
- <Button
- android:text="Connect"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/btnConnect" />
- </LinearLayout>
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)
- public class Connect : Activity
- {
- private EditText edtIp, edtport;
- private Button btnConnect;
- private TcpClient client;
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
- client = new TcpClient();
-
- SetContentView(Resource.Layout.Connect);
- edtIp = FindViewById<EditText>(Resource.Id.edtIpAddress);
- edtport = FindViewById<EditText>(Resource.Id.edtPort);
- btnConnect = FindViewById<Button>(Resource.Id.btnConnect);
- btnConnect.Click += async delegate
- {
- try
- {
- await client.ConnectAsync(edtIp.Text, Convert.ToInt32(edtport.Text));
- if (client.Connected)
- {
- Connection.Instance.client = client;
- Toast.MakeText(this, "Client connected to server!", ToastLength.Short).Show();
- Intent intent = new Intent(this, typeof(Control));
- StartActivity(intent);
- }
- else
- {
- Toast.MakeText(this, "Connection feild!", ToastLength.Short).Show();
- }
- }
- catch (Exception x)
- {
- Toast.MakeText(this, "Connection feild!", ToastLength.Short).Show();
- Toast.MakeText(this, "" + x, ToastLength.Short).Show();
- }
- };
- }
- }
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.
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)
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:padding="20dp">
-
- <Button
- android:text="Sleep"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/btnSleep" />
-
- </LinearLayout>
Step 2 - Add Activity for Control
Add a new activity with the name Control.cs and replace the following code.
- public class Control : Activity
- {
- private Button btnSleep;
-
- NetworkStream stream;
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
- var client = Connection.Instance.client;
-
- SetContentView(Resource.Layout.Control);
- btnSleep = FindViewById<Button>(Resource.Id.btnSleep);
-
- btnSleep.Click += delegate
- {
- stream = client.GetStream();
- String s = "SLP2";
- byte[] message = Encoding.ASCII.GetBytes(s);
- stream.Write(message, 0, message.Length);
- };
- }
- }
Connect with the server and press the Sleep button. Your workstation will go to the sleep mode. In the next part, I will complete all my project functionality. So, please stay tuned for my next article of this series.