日期:2014-05-18 浏览次数:20896 次
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Threading; using System.Net.Sockets; namespace UDP广播2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false;//允许交差线程访问(没这个就不能在别的进程修改textBox了) } EndPoint ep; string receiveData; Socket socket; private void Acc() { socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 8899); socket.Bind(iep); ep = (EndPoint)iep; byte[] bytes = new byte[1024]; byte[] initbytes = new byte[1024]; while (true) { try { initbytes.CopyTo(bytes,0); socket.ReceiveFrom(bytes, ref ep); receiveData = System.Text.Encoding.Unicode.GetString(bytes); receiveData = receiveData.TrimEnd('\u0000'); if (receiveData.Length > 0) { richTextBox1.Text = "来自" + ep.ToString() + "的消息" + receiveData; } } catch { break; } } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { socket.Close(); } Socket socket2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//只能用UDP协议发送广播,所以ProtocolType设置为UDP IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 8899); //让其自动提供子网中的IP地址 byte[] bytes; private void button2_Click(object sender, EventArgs e) { bytes = Encoding.Unicode.GetBytes(textBox1.Text); //将发送内容转换为字节数组 textBox1.Text = ""; socket2.SendTo(bytes, iep); } private void button1_Click(object sender, EventArgs e) { socket2.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); //设置broadcast值为1,允许套接字发送广播信息 button1.Enabled = false; Thread th = new Thread(new ThreadStart(Acc)); th.Start(); } } }