I recently acquired an IPAD and in my quest to take over the world control my immediate environment I figured that it makes a pretty good tool. Unfortunately without jail breaking the device or paying lots of money for a SCADA app, there aren’t a lot of development possibilities for the IPAD.
After a bit of research I managed to find a app called Net Remote. It’s essentially a remote control app which connects to a tcp server on the network. Whenever a button is pressed it sends a message to the server and the server performs an action. Another great feature of this app is that you can create custom layouts for it, basically design the remote with your own custom buttons and designs.
The only drawback of this application is that the server side applications are created for a mac (no windows/linux) and also don’t really have the functionalities that I am interested in, so I decided to develop my own.
To make the process easier I created a small basic class that creates a socket and listens for incoming commands from the remote. It generates an event for each incoming action. This class is by no means complete (error checking,etc) but you get the idea on how it works.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
namespace tcpservertest
{
public class tcpserver
{
private TcpListener tcpListener;
private Thread listenThread;
// delegate declaration
public delegate void OnIncomingActionHandler(object sender, ActionArgs Aa);
public event OnIncomingActionHandler OnIncomingAction;
public tcpserver(int PortNumber)
{
this.tcpListener = new TcpListener(IPAddress.Any, PortNumber);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
}
public void StartServer()
{
this.listenThread.Start();
}
public void StopServer()
{
this.listenThread.Abort();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
// blocking
TcpClient client = this.tcpListener.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientCom));
clientThread.Start(client);
}
}
private void HandleClientCom(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
// socket error
}
if (bytesRead == 0)
{
// client has been disconnected
break;
}
ASCIIEncoding encoder = new ASCIIEncoding();
ActionArgs Aa = new ActionArgs(encoder.GetString(message, 0, bytesRead));
if (this.OnIncomingAction != null)
OnIncomingAction(this, Aa);
}
}
}
public class ActionArgs : System.EventArgs
{
private string message;
public ActionArgs(string m)
{
this.message = m;
}
public string Message()
{
return message;
}
}
}
Enjoy