private UdpClient sendUdp;
private IPEndPoint LocalHostIep;
private static int IPProt = 8300;
public Form1()
{
InitializeComponent();
try
{
string strHostName = Dns.GetHostName(); //得到主机的主机名
IPHostEntry ipEntry = Dns.GetHostByName(strHostName); //取得本机IP
string LocalHostIP = ipEntry.AddressList[0].ToString();
LocalHostIep = new IPEndPoint(IPAddress.Parse(LocalHostIP), IPProt); //指定UDP信息发送的主机网卡IP
sendUdp = new UdpClient(LocalHostIep);
}
catch
{
MessageBox.Show("端口被占用");
this.Close();
}
}
/// <summary>
///发送
/// </summary>
private void SendUDP_Click(object sender, EventArgs e)
{
try
{
byte[] Byte = new byte[512];
Array.Copy(Encoding. Default.GetBytes("你好"), Byte,4); //字符串转byte,再写入到Byte[]
string str = "abcdefg";
Array.Copy(Encoding.ASCII.GetBytes(str), 0, Byte, 7, str.Length()); //字符串转byte,再
写入到Byte[]中,从第7位开始写入
IPEndPoint iep= new IPEndPoint(IPAddress.Parse(“192.168.68.88”), IPProt);
//IPEndPoint iep= new IPEndPoint(IPAddress. Broadcast, IPProt); //发送广播包
sendUdp.Send(Byte, Byte.Length, iep, IPProt));
//使用线程接收返回的信息
Thread threadUdpReceive = new Thread(new ThreadStart(ReceiveUDP));
threadUdpReceive.IsBackground = true;
threadUdpReceive.Start();
Thread.Sleep(1000); //暂停1秒后关闭线程
if (threadUdpReceive.IsAlive)
{
threadUdpReceive.Abort();
}
}
catch (SystemException ex)
{
}
}
/// <summary>
///接收信息
/// </summary>
private void ReceiveUDP()
{
try
{
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0); //可以接收任何IP地址发过来的信息
while (true)
{
byte[] buff = sendUdp.Receive(ref Search_iep);//接收消息
字符串数组怎么转成byte///数据处理,如”你好”:strint str= Encoding.Default.GetString(buff, 0, 4);
}
}
catch (SystemException ex)
{
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论