C# 创建一个线程,每秒用udp发送一次数据。代码怎么写?
1个回答
展开全部
public class Class1
{
bool sending = true;
public void Send()
{
var t = new System.Threading.Thread(new System.Threading.ThreadStart(()=> {
using (var udpClient = new System.Net.Sockets.UdpClient())
{
while (sending)
{
udpClient.Connect("127.0.0.1", 8080);//IP,端口号
byte[] diagram = UTF8Encoding.ASCII.GetBytes("HELLO!");//这是要发送的内容
udpClient.Send(diagram, diagram.Length);
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));//发送的间隔
}
}
}));
t.Name = "发送数据包";
t.Start();
}
public void Stop()
{
sending = false;
}
}
{
bool sending = true;
public void Send()
{
var t = new System.Threading.Thread(new System.Threading.ThreadStart(()=> {
using (var udpClient = new System.Net.Sockets.UdpClient())
{
while (sending)
{
udpClient.Connect("127.0.0.1", 8080);//IP,端口号
byte[] diagram = UTF8Encoding.ASCII.GetBytes("HELLO!");//这是要发送的内容
udpClient.Send(diagram, diagram.Length);
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));//发送的间隔
}
}
}));
t.Name = "发送数据包";
t.Start();
}
public void Stop()
{
sending = false;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询