做了一个winform程序,同时发送和接收包,代码如下: //调用流程:客户端使用定时器开线程,先清空ALConnectedIp,然后执行SendUdpPackage方法,第一参数为对方ip,第二个参数为"AreUonline"
public void UdpListener()
{
Thread.Sleep(30);
while(true)
{
IPEndPoint endpoint = null;
Byte[] data = thisUdpClient.Receive(ref endpoint); if(data!=null)
{
string s=Encoding.UTF8.GetString(data);
//如果是询问自己是否在线
if(s.Split('@')[0]=="AreUonline")
{
//向询问方发送我在线
SendUdpPackage(s.Split('@')[1],"Yeah");
MessageBox.Show(s.Split('@')[1]+"询问您在不在线");
}
else if(s.Split('@')[0]=="Yeah")
{
ALConnectedIp.Add(s.Split('@')[1]);
//MessageBox.Show(s.Split('@')[1]);
}
}
}
}
public void SendUdpPackage(string strIp,string cmdType)
{ if( IsValidIP(strIp) )
{
IPAddress ip = IPAddress.Parse(strIp);
IPEndPoint ipend = new IPEndPoint(ip, udpPort);
//定义发送目的终结点,将自己地址告诉接收方
Byte[] bt = Encoding.UTF8.GetBytes(cmdType+"@"+localIp);
//把textBox1的文本用ASCII编码
thisUdpClient.Send(bt, bt.Length, ipend);
}
}前台定时器中循环调用:
SendUdpPackage("本机ip","AreUonline");
SendUdpPackage("另外机子的ip,没运行该程序","AreUonline");则只弹出一次提示框就不继续弹了,如果只有SendUdpPackage("本机ip","AreUonline");则可以按定时器指定的时间间隔弹出提示框不知是发包还是收包阻塞了,该怎么解决该问题呢?
public void UdpListener()
{
Thread.Sleep(30);
while(true)
{
IPEndPoint endpoint = null;
Byte[] data = thisUdpClient.Receive(ref endpoint); if(data!=null)
{
string s=Encoding.UTF8.GetString(data);
//如果是询问自己是否在线
if(s.Split('@')[0]=="AreUonline")
{
//向询问方发送我在线
SendUdpPackage(s.Split('@')[1],"Yeah");
MessageBox.Show(s.Split('@')[1]+"询问您在不在线");
}
else if(s.Split('@')[0]=="Yeah")
{
ALConnectedIp.Add(s.Split('@')[1]);
//MessageBox.Show(s.Split('@')[1]);
}
}
}
}
public void SendUdpPackage(string strIp,string cmdType)
{ if( IsValidIP(strIp) )
{
IPAddress ip = IPAddress.Parse(strIp);
IPEndPoint ipend = new IPEndPoint(ip, udpPort);
//定义发送目的终结点,将自己地址告诉接收方
Byte[] bt = Encoding.UTF8.GetBytes(cmdType+"@"+localIp);
//把textBox1的文本用ASCII编码
thisUdpClient.Send(bt, bt.Length, ipend);
}
}前台定时器中循环调用:
SendUdpPackage("本机ip","AreUonline");
SendUdpPackage("另外机子的ip,没运行该程序","AreUonline");则只弹出一次提示框就不继续弹了,如果只有SendUdpPackage("本机ip","AreUonline");则可以按定时器指定的时间间隔弹出提示框不知是发包还是收包阻塞了,该怎么解决该问题呢?
所以如果对方没开机对你没有任何影响