bs结构socket(udp)通信
以前我所做的基于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, recv)); //客户机连接成功后,发送信息 string welcome = "hello,sean! "; //字符串与字节数组相互转换 data = Encoding.ASCII.GetBytes(welcome); //发送信息 newsock.SendTo(data, data.Length, SocketFlags.None, Remote); while (true) { data = new byte[1024]; //发送接收信息 recv = newsock.ReceiveFrom(data, ref Remote); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); newsock.SendTo(data, recv, SocketFlags.None, Remote); } #endregionbs客户端(实际是发布iis所在的服务器):
public partial class _Default : System.Web.UI.Page { string host = ""; int port = 0; protected void Page_Load(object sender, EventArgs e) { } protected void Button2_Click(object sender, EventArgs e) { //int port = 5154; //host = "172.16.2.245"; port = Int32.Parse(this.txt_port.Value.Trim()); host = this.txt_ip.Value.Trim(); //创建终结点EndPoint IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port); //把ip和端口转化为IPEndPoint的实例 UdpClient sender1 = new UdpClient(); //向服务器发送信息 string sendStr = this.txt_info.Value; byte[] bs = Encoding.ASCII.GetBytes(sendStr); //把字符串编码为字节 lock (this) { sender1.Send(bs, bs.Length, ipe); this.txt_info.Value = ""; Thread.Sleep(200); Receive(sender1); } } public void Receive(UdpClient sender1) { IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any,2000); try { Byte[] receiveBytes = sender1.Receive(ref RemoteIpEndPoint); string returnData = Encoding.ASCII.GetString(receiveBytes); this.txt_info.Value=("message received " +returnData.ToString()); } catch (Exception e) { } } }需要考虑并发操作,我在前台有相关操作限制,特殊情况特殊考虑
学无先后,达者为师