天天看點

vb.net的socket通信

private sub ClientThread(ByVal clientParam as object)

dim param as clientThreadParam

param=CType(clientParam,ClientThreadParam)

dim isAuthorizedClient as boolean=false

dim bytes(MaxBufferSize-1) as byte

dim recvBuffer(MaxBufferSize*MaxNumberOfBuffers-1) as byte

dim lens as Integer =1

dim loopFlg as Integer=0

'循環體内,開始接收資料

do until(lens<=0 or loopFlg>0)

   dim packetLength as short=0

   dim offset as integer =0

  try

    lens=param.clientSocket.Receive(bytes)

   catch ex as Exception

    try

      if(param.clientSocket.connected) then

          param.clientSocket.close()

      end if

     catch ex1 as exception

   end try

if (lens=CmdFrameLength and not isAuthorizedClient) then

'認證處理過程

else if(lens>CmdFrameLength and isAuthorizedClient) then

'資料包接收過程

     if(Not byte(3)=CmdCode0x57) then

       param.clientSocket.close()

       loopFlg=1

     end if

  try

    packetLength=getPacketLength(bytes,me.bigCode.checked)

   catch ex as exception

     param.clientSocket.close()

    loopFlg=1

  end try

  '将接收到的資料,儲存于緩沖區recvbuffer内

  buffer.blockCopy(bytes,0,recvBuffer,offset,lens)

  offset=offset+lens

 '如果所接收到的包小于所定義的包的長度,繼續接收

 do until(offset=packetLength)

      try

      lens=param.clientSocket.receive(bytes)

      offset=offset+lens

       catch ex as exception

          try

           if(param.clientSocket.connected) then

             param.clientSocket.disconnect(true)

          end if

            loopFlg=1

       return

     end try

Loop

 '分析所接收到的資料

  AnalysisFrame(recvBuffer,packetLength,ipaddr)