udp广播怎么接收
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();
}
}
}