C# UDP广播启动服务和客户端【Socket】
服务端: Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // 初始化一个Scoket协议 IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9095); // 初始化一个侦听局域网内部所有IP和指定端口 EndPoint ep = (EndPoint)iep; socket.Bind(iep); // 绑定这个实例 while (true) { byte[] buffer = new byte[1024];//设置缓冲数据流 socket.ReceiveFrom(buffer, ref ep);//接收数据,并确把数据设置到缓冲流里面 Console.WriteLine(Encoding.Unicode.GetString(buffer) + " " + DateTime.Now.ToString()); }
客户端 Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // 初始化一个Scoket实习,采用UDP传输 IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 9095); // 初始化一个发送广播和指定端口的网络端口实例 sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); // 设置该scoket实例的发送形式 string request = "222"; // 初始化需要发送而的发送数据 byte[] buffer = Encoding.Unicode.GetBytes(request); sock.SendTo(buffer, iep); sock.Close();