我有一个class,用于与一些硬件设备(准确地说是步进电机)进行通信:
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();
}
}我现在就是这么用的:
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();
}我是否正确地使用了TCP Client?我特别关心溪流的使用和处理。我做得对吗?
发布于 2014-11-11 13:40:29
恐怕我对TCP一无所知,但我确实注意到了这一点。
如果(!client.Connected) {/*忽略*/}Console.WriteLine(“侦听器错误:”+ ex.Message);}
与其检查阴性条件,不如检查是否为阳性。它删除了几行代码和一个注释。
if(client.Connected)
{
Console.WriteLine("Listener error: " + ex.Message);
}发布于 2014-11-11 13:53:43
由于HDCommunicator类实现了IDisposable,所以应该将代码包装在using块中,如下所示:
static void Main(string[] args)
{
using (var 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));
}
}
Console.WriteLine("Finished");
Console.ReadLine();
}这样,您就不需要手动处理对象了: using块为您完成了这个任务。
我发现使用string.Empty比使用""更干净:
string res = string.Empty为了确保一致性,即使在条件语句上也应该使用大括号,如下所示:
if (res != "e")
{
comm.SendCommand(int.Parse(res));
}您应该避免使用缩写或缩短的术语,并将comm重命名为hdCommunicator或communicator。缩写变量名在它们的生存期很短的时候是可以的,就像lambda表达式中的一样。
发布于 2014-11-11 13:47:01
Thread t = new Thread(new ThreadStart(() => { Listen(); }));
t.Start();因为Listen不接受参数,所以没有必要使用lambda。您可以将其改写为:
new Thread(Listen).Start();https://codereview.stackexchange.com/questions/69472
复制相似问题