用UDP协议发送广播
服务器端:发送消息 private void button1_Click(object sender, EventArgs e) { //只能用UDP协议发送广播,所以ProtocolType设置为UDP Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //让其自动提供子网中的IP地址 //IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.1.13"), 8090);//IPAddress.Broadcast IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 8090);//IPAddress.Broadcast //设置broadcast值为1,允许套接字发送广播信息 socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); //将发送内容转换为字节数组 byte[] bytes = System.Text.Encoding.Unicode.GetBytes(this.textBox1.Text); //向子网发送信息 socket.SendTo(bytes, iep); socket.Close(); }
客户端:接收消息 //接收信息 private void AcceptMessage() { //d定义socket对象 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.0.105"), 8090); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 8090); socket.Bind(iep); ep = (EndPoint)iep; Console.WriteLine("Ready to receive…"); byte[] bytes; while (true) { stringData = ""; int recv = 0; bytes = new byte[1024]; try { recv = socket.ReceiveFrom(bytes, ref ep); } catch (Exception ex) { Console.WriteLine("有异常", ex.ToString()); } //string stringData = Encoding.ASCII.GetString(bytes, 0, recv); stringData = System.Text.Encoding.Unicode.GetString(bytes).TrimEnd('\u0000'); Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString()); //socket.ReceiveFrom(bytes, ref ep); //receiveData = System.Text.Encoding.Unicode.GetString(bytes); //receiveData = receiveData.TrimEnd('\u0000'); //Thread th = new Thread(new ThreadStart(Acc)); //th.Start(); } socket.Close(); }