udp广播怎么接收

mlimlimu 2008-03-19 01:36:32
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public delegate void mydelegate(string s );
public Thread my ;
public string myip;
public string myName="Emily";
public const int port1 = 555;
// public UdpClient accept;
public void mf()
{
mydelegate mm = delegate(string s) { listen(); };

}


public void listen()
{
UdpClient accept = new UdpClient(port1);

try
{
IPEndPoint iep3 = new IPEndPoint(IPAddress.Any, 555);
while (true)
{
Byte[] message = accept.Receive(ref iep3);
this.richTextBox1.AppendText(message.ToString ());
richTextBox1.ScrollToCaret();
}

}
catch (System.Security.SecurityException)
{
MessageBox.Show("防火墙安全错误!", "错误",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
catch (Exception f)
{
MessageBox.Show(f.Message);
}
finally
{
accept.Close();
}

}

public void send()
{
try
{
Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.53.255"),port1);
sock.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Broadcast,1);
sock.SendTo(System.Text.Encoding.Unicode.GetBytes(textBox1.Text), iep2);
sock.Close();
string msg = myName + ":" + DateTime.Now.ToString("T") + "\r\n" + textBox1.Text + "\n";
this.richTextBox1.AppendText(msg);
this.richTextBox1.ScrollToCaret();
textBox1.Clear();
}
catch (Exception ff)
{
MessageBox.Show(ff.Message);
}
}

public Form1()
{
InitializeComponent();
my = new Thread(new ThreadStart(mf));
my.Start();
}

private void button1_Click(object sender, EventArgs e)
{

}

private void Form1_Load(object sender, EventArgs e)
{

}

private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length == 0)
{
button3.Enabled = false;
}
else button3.Enabled = true;
}

private void richTextBox1_TextChanged(object sender, EventArgs e)
{

}

private void button2_Click(object sender, EventArgs e)
{

}

private void 帮助ToolStripMenuItem_Click(object sender, EventArgs e)
{

}

private void button3_Click(object sender, EventArgs e)
{
send();

}
}

}
...全文
107 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
mlimlimu 2008-03-20
  • 打赏
  • 举报
回复
恩,谢谢了,做出来了。
vrhero 2008-03-19
  • 打赏
  • 举报
回复
UdpClient可以向任何网络广播地址广播但它无法侦听发送到网络的广播...必须使用Socket类才能侦听网络广播...

另外广播消息必须发送到广播地址...UdpClient只能侦听多路广播地址组的UDP广播...
whmjw 2008-03-19
  • 打赏
  • 举报
回复
IPEndPoint iep3 = new IPEndPoint(IPAddress.broadcast, 555);

17,740

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 .NET Framework
社区管理员
  • .NET Framework社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧