一個合做夥伴說UDP發送數據,A(IP:192.168.1.100 子網掩碼255.255.255.0)網段能發數據到B網段,但B(IP:192.168.2.100 子網掩碼255.255.255.0)網段不能發數據到A網段,說法是跨路由的狀況下,數據只能從下層住上層發,而不能由上層住下層發。我以爲兩個網段的地位應該是相等的,即便跨路由的狀況下,也應該有路由映射能夠讓這兩個網段相互能夠ping通,而只要兩個網段能夠ping通,就能夠用upd發送數據 (固然,咱們說的前提都是在一個公司的局域網內),而發送數據應該沒有什麼上層網段和下層網段這個玄乎的概念了吧!(哎,網絡不懂害死人呀!),因而,這個測試程序就產生了,目的就是看看在任意兩個能夠ping通的網段裏是否能夠收發數據。網絡
源碼以下:測試
namespace Clint2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("請設置IP地址:");
string ip = Console.ReadLine();
UDPTest udpTest = new UDPTest(ip);
Console.WriteLine("請輸入要發送的數據");
string key = Console.ReadLine();
while (key != "ok")
{
udpTest.AddQueue(key);
Console.WriteLine("請輸入要發送的數據");
key = Console.ReadLine();
}
udpTest.StopSend();
}this
}spa
public class UDPTest
{線程
Queue<string> _queue = new Queue<string>();
UdpClient clintReceive = new UdpClient(8801); //接收
UdpClient clintSend = new UdpClient(); //發送
IPEndPoint romoteIP;
bool _isStartSend;
Thread threadSend;ip
public UDPTest(string ip)
{
romoteIP = new IPEndPoint(IPAddress.Parse(ip), 8801);路由
//啓動發送線程
_isStartSend = true;
threadSend = new Thread(new ThreadStart(Send));
threadSend.IsBackground = true;
threadSend.Start();源碼
//開始接收數據
Receive();
}string
public void StopSend()
{
_isStartSend = false;it
clintReceive.Close();
clintSend.Close();
}
public void Receive()
{
clintReceive.BeginReceive(ReceiveCallback, clintReceive);
}
public void ReceiveCallback(IAsyncResult ar)
{
IPEndPoint tmpRomeIP = null;
UdpClient cr = ar.AsyncState as UdpClient;
byte[] receiveData = cr.EndReceive(ar, ref tmpRomeIP);
string str = Encoding.ASCII.GetString(receiveData);
Console.WriteLine(str + " from IP: " + tmpRomeIP.Address.ToString() +
" port: " + tmpRomeIP.Port.ToString()
);
Receive();
}
public void Send()
{
clintSend.Connect(romoteIP);
while (_isStartSend)
{
while (_queue.Count > 0 && _isStartSend)
{
string strValue = DeQueue();
byte[] sendData = Encoding.ASCII.GetBytes(strValue);
//clintSend.Send(sendData, sendData.Length, romoteIP);
clintSend.BeginSend(sendData, sendData.Length, SendCallback, clintSend);
}
Thread.Sleep(500);
}
}
public void SendCallback(IAsyncResult ar)
{
UdpClient cr = ar.AsyncState as UdpClient;
cr.EndSend(ar);
}
public void AddQueue(string str)
{
lock (this)
{
_queue.Enqueue(str);
}
}
public string DeQueue()
{
lock (this)
{
return _queue.Dequeue();
}
}
}}