【发布时间】:2015-03-27 12:15:38
【问题描述】:
我需要检查本地网络中任何计算机的状态。但是我的代码无效,因为响应时间很长。我尝试了线程,该检查器在后台运行。但我需要更快的检查。我的程序作为客户端服务器运行。
在我的主程序中,我需要将可用的计算机写入 listbox。 示例:
我的主要客户想要获得本地网络中的可用计算机。计算机在端口 13000 上运行服务器。但是,当我想找出可用的计算机时,响应太长了。
变量
string message = "!";
string temp = "";
public static string list = "";
检查可用计算机:
public static void checker()
{
string IP;
int statResp = 0;
for (int i = 1; i < 10; i++)
{
IP = "192.168.0." + i;
string msg = "!";
try
{
Int32 port = 13000;
TcpClient client = new TcpClient(IP, port);
Byte[] data = System.Text.Encoding.ASCII.GetBytes(msg);
msg = "!";
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
data = new Byte[256];
String responseData = String.Empty;
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
if (responseData == " " || responseData == "!")
{
statResp = 1; // response is correct server runs
}
stream.Close();
client.Close();
}
catch (ArgumentNullException)
{
continue; // continue with next iteration
}
catch (SocketException)
{
continue; // continue with next iteration
}
if (statResp == 1)
{
list = IP; // list is variable
}
}
}
TIMER - 检查 list 变量中的数据
private void timer2_Tick(object sender, EventArgs e)
{
if (temp != list)
{
listBox1.Items.Add(list);
temp = list;
}
}
如果 list 变量的值与 temp 变量中的值相同,则不会将旧地址添加到列表中。
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
标签: c# .net client server status