C# Socket数据接收的三种实现方式

  int recv;//定义接收数据长度变量

  IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text));

  //接收端所监听的接口,ip也可以用IPAddress.Any

  Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

  //初始化一个Socket对象

  socket.Bind(ipEnd);//绑定套接字到一个IP地址和一个端口上(bind());

  socket.Listen(10);

  while (true)

  {

  byte[] data = new byte[1024];//对data清零

  Socket clientSocket = socket.Accept(); //一旦接受连接,创建一个客户端

  recv = clientSocket.Receive(data);

  if (recv == 0) //如果收到的数据长度小于0,则退出

  break;

  string stringData = "0x" + BitConverter.ToString(data).Replace("-", " 0x").ToLower();

  this.Invoke((EventHandler)delegate

  {

  richTextBox1.Text += DateTime.Now.ToString("yy-MM-dd hh:mm:ss") + stringData + "

  ";

  });

  }