I have a class
that I use to communicate with some hardware equipment (a step motor to be precise):
public class HdCommunicator : IDisposable
{
private TcpClient client;
public HdCommunicator(TcpClient _client)
{
client = _client;
//create and start the listener
Thread t = new Thread(new ThreadStart(() => { Listen(); }));
t.Start();
}
public void SendCommand(int data)
{
NetworkStream ns = client.GetStream();
var msgToSend =
Encoding.UTF8.GetBytes("mr " + data + ",1" + Environment.NewLine);
ns.Write(msgToSend, 0, msgToSend.Length);
ns.Flush();
}
private void Listen()
{
while (client.Connected)
{
try
{
NetworkStream ns = client.GetStream();
byte[] bytes = new byte[1024];
int bytesRead = ns.Read(bytes, 0, bytes.Length);
string response = Encoding.ASCII.GetString(bytes, 0, bytesRead);
//TODO raise event
Console.WriteLine("Response: " + response);
}
catch (Exception ex)
{
if (!client.Connected)
{ /*ignore*/ }
else
{
Console.WriteLine("Listener error: " + ex.Message);
}
}
}
}
public void Dispose()
{
client.Close();
}
}
And this is how I currently use it:
static int port = 503;
static string host = "192.168.33.1";
static void Main(string[] args)
{
HdCommunicator comm = new HdCommunicator(new TcpClient(host, port));
string res = "";
while (res != "e")
{
Console.WriteLine("Where to send: ");
res = Console.ReadLine();
if (res != "e")
comm.SendCommand(int.Parse(res));
}
comm.Dispose();
Console.WriteLine("Finished");
Console.ReadLine();
}
Am I utilizing the TCP Client
correctly? I'm particularly concerned about the streams' usage and disposing of them. Am I doing it right?