HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

TCP communication with step motor

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withcommunicationtcpstepmotor

Problem

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("Finis

Solution

I'm afraid that I don't know anything about TCP, but I did notice this.

if (!client.Connected)
  { /*ignore*/ }
  else
  {
     Console.WriteLine("Listener error: " + ex.Message);
  }


Instead of checking for the negative condition, check for the positive. It removes several lines of code and a comment.

if(client.Connected)
{
    Console.WriteLine("Listener error: " + ex.Message);
}

Code Snippets

if (!client.Connected)
  { /*ignore*/ }
  else
  {
     Console.WriteLine("Listener error: " + ex.Message);
  }
if(client.Connected)
{
    Console.WriteLine("Listener error: " + ex.Message);
}

Context

StackExchange Code Review Q#69472, answer score: 5

Revisions (0)

No revisions yet.