以前我所做的基于socket通信都是采用cs结构,现公司有一个项目需要在bs中反控设备,于是研究了一番,现将成果公布,方便以后查阅。
服务端:
#region udp
int recv;
byte[] data = new byte[1024];
//得到本机IP,设置TCP端口号
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 2000);
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//绑定网络地址
newsock.Bind(ip);
//等待客户机连接
Console.WriteLine("This is a Server,Waiting for a client);
//得到客户机IP
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
recv = newsock.ReceiveFrom(data, ref Remote);
Console.WriteLine("Message{0}: ", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, r