static void thrDataSend() {//线程入口 //线程流程 IPEndPoint remoteEP = new IPEndPoint(ServerIP, Int32.Parse("8131")); // Create a TCP/IP socket. client_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { client_sock.Blocking = true; client_sock.Connect(remoteEP); RecvDataBuf = new byte[1024]; Accep_Object Ac_state = new Accep_Object(); client_sock.BeginReceive( RecvDataBuf, 0, 1024, SocketFlags.None, new AsyncCallback(ReceiveCallback), Ac_state); //数据暂存缓存,开始数据打包 byte[] SendDataBuffer = new byte[1024]; try { int iRetValue; iRetValue = WaitHandle.WaitAny(mreArray, 500); while (iRetValue != 0) { switch (iRetValue) { case 1: //有数据要发送 //消费本次发送事件 mreDataSend.Reset(); //1将数组值清空 Array.Clear(SendDataBuffer, 0, 1024); byte[] bChatText = Encoding.UTF8.GetBytes(strChatText); //client_sock Array.Copy(bChatText, 0, SendDataBuffer, 0, bChatText.Length); client_sock.Send(SendDataBuffer, bChatText.Length, SocketFlags.None); break; default: break; } iRetValue = WaitHandle.WaitAny(mreArray, 500); } } catch (SocketException se3) { MessageBox.Show("客户端异常3" + se3.Message); } } catch (SocketException se1) { MessageBox.Show("SocketException" + se1.Message); MessageBox.Show(se1.ErrorCode.ToString()); //10061 //Winsock Reference //WSAECONNREFUSED 10061 //Winsock2.h } catch (Exception se2) { MessageBox.Show("客户端异常1" + se2.Message); } }
void ConnectCallback(IAsyncResult ia) { buff = new byte[1024]; clientSocket = (Socket)ia.AsyncState; clientSocket.BeginReceive(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), clientSocket); }
private void Begin_Receive(IAsyncResult ar) { if (ClientSocket != null) { try { ClientSocket.EndReceive(ar); byte[] Header = lengthBUFF; int length = BitConverter.ToInt32(Header, 0); byte[] Payload = ReceiveData(length, ClientSocket); if (Header.Length == 4 && Payload.Length == length) { Data DTU = Data.Desserialize(Payload); if (DTU.type != 0) { if (DTU.type == 1) { Rectangle bounds = new Rectangle(DTU.bx, DTU.by, DTU.bwidth, DTU.bheight); Image restoreIMG; if (DTU.comp) { restoreIMG = LZ4mm.LZ4Codec.Decode32(DTU.dataBytes, 0, DTU.dataBytes.Length, DTU.dataSize) .toBitmap(); } else { restoreIMG = (Bitmap)DTU.dataBytes.toBitmap(); } if (!firstImage) { oldImage = (Bitmap)restoreIMG; firstImage = true; } else { Utils.UpdateScreen(ref oldImage, restoreIMG, bounds); } } else if (DTU.type == 2) { oldImage = (Bitmap)DTU.dataBytes.toBitmap(); } this.pictureBox1.Image = oldImage; FPS++; if (fpsCounter.ElapsedMilliseconds >= 1000) { this.Invoke(new MethodInvoker(() => { this.lblFPS.Text = FPS.ToString(); })); FPS = 0; fpsCounter = Stopwatch.StartNew(); } } } } catch (Exception ex) { //MessageBox.Show("Exception: " + ex.Message); } try { if (ClientSocket.Connected) { ClientSocket.BeginReceive(lengthBUFF, 0, lengthBUFF.Length, SocketFlags.None, Begin_Receive, null); } } catch (Exception ex) { Connect(false); //MessageBox.Show("Exception: " + ex.Message); } } }