110,538
社区成员
发帖
与我相关
我的任务
分享
public frmMain mainForm;
private static Thread ClientRecThread;
bool bReceiving = false;
private UdpClient recvUdpClient=null;
private UdpClient sendUdpClient=null;
IPEndPoint remoteIPE = null;
IPEndPoint localIPE = null;
private ManualResetEvent sendDone = new ManualResetEvent(false);
private ManualResetEvent recvDone = new ManualResetEvent(false);
UdpState udpRecvState = null;
UdpState udpSendState = null;
public UdpClientClass(string strLocalIp, int nLocalPort,string strTargetIp,int nTargetPort,string strNetMask,string strGateWay)
{
localIPE = new IPEndPoint(IPAddress.Any, nLocalPort);
remoteIPE = new IPEndPoint(IPAddress.Parse(strTargetIp), nTargetPort);
recvUdpClient = new UdpClient(localIPE);
sendUdpClient = new UdpClient();
udpRecvState = new UdpState();
udpRecvState.ipEndPoint = localIPE;
udpRecvState.udpclient = recvUdpClient;
udpSendState = new UdpState();
udpSendState.ipEndPoint = remoteIPE;
sendUdpClient.Connect(udpSendState.ipEndPoint);
udpSendState.udpclient = sendUdpClient;
StartLisnProc();
}
private void StartLisnProc()
{
bReceiving = true;
ClientRecThread = new Thread(new ThreadStart(RecvData));
ClientRecThread.IsBackground = true;
ClientRecThread.Start();
}
private void RecvData()
{
while(bReceiving)
{
lock (this)
{
IAsyncResult iar = recvUdpClient.BeginReceive(new AsyncCallback(asycRecvCallback), udpRecvState);
recvDone.WaitOne();
}
}
}
private void asycRecvCallback(IAsyncResult iar)
{
UdpState udpState = iar.AsyncState as UdpState;
if (iar.IsCompleted)
{
byte[] recvBytes = udpState.udpclient.EndReceive(iar, ref udpRecvState.ipEndPoint);
string strRecv = ByteToString(recvBytes);
if (recvBytes.Length > 0)
{
mainForm.UpdateState(strRecv, recvBytes.Length);
}
recvDone.Set();
}
}