110,561
社区成员
发帖
与我相关
我的任务
分享
Thread th;//UDP线程
Thread thread;//接收线程
private void btnFirst_Click(object sender, EventArgs e)
{
int parem = 0;
th = new Thread(UDPServertStart);
th.IsBackground = true;
th.Start(parem);
}
/// <summary>
/// 程序开始实时数据(UDP模式)
/// </summary>
public void UDPServertStart(object o)
{
try
{
IPAddress ipAddress = IPAddress.Parse(Udpip);
IPLocalPoint = new IPEndPoint(ipAddress, Udpport);
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
mySocket.Bind(IPLocalPoint);
//得到客户机IP
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
RemotePoint = (EndPoint)(ipep);
//启动一个新的线程
thread = new Thread(new ThreadStart(ReceiveHandle));
thread.Start();
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
return;
}
}
/// <summary>
/// 接收信息
/// </summary>
public void ReceiveHandle()
{
ByteQueue queue = new ByteQueue();
string host = getIPAddress();
while (true)
{
try
{
byte[] data = new byte[1024];
//接收UDP数据报,引用参数RemotePoint获得源地址
int rlen = mySocket.ReceiveFrom(data, ref RemotePoint);
//分多次接收
byte[] reallData = new byte[rlen];
Array.Copy(data, reallData, reallData.Length);
queue.Enqueue(reallData);
queue.headBuffer = new byte[] { 0xCA, 0xCB, 0xCC, 0xCD }; //包头开始部份
while (queue.Find())
{
byte[] readBuffer = queue.Dequeue();
}
}
catch (Exception ex)
{
return;
}
finally
{
}
}
}
public void UDPServertStart(object o)
{
try
{
IPAddress ipAddress = IPAddress.Parse(Udpip);
IPLocalPoint = new IPEndPoint(ipAddress, Udpport);
if (mySocket == null)
{
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
mySocket.Bind(IPLocalPoint);
//得到客户机IP
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
RemotePoint = (EndPoint)(ipep);
if (thread == null || !thread.IsAlive)
{
//启动一个新的线程
thread = new Thread(new ThreadStart(ReceiveHandle));
thread.Start();
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
return;
}
}
接收线程照你逻辑不用每次都创建,而Socket.Bind好像有必要重新绑,不知道IP端口会不会随时变