接收
完成端口是结合重叠端口一起使用的,在接收数据之前,我们需要投递一个接收请求,使用function WSARecv(s: TSocket; lpBuffers: LPWSABUF; dwBufferCount: DWORD; var lpNumberOfBytesRecvd, lpFlags: DWORD; lpOverlapped: LPWSAOVERLAPPED; lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE): Integer函数,接收连接后,就需要投递一个请求,代码如下:
procedure TSocketHandle.PreRecv(AIocpRecord: PIocpRecord); var iFlags, iTransfer: Cardinal; iErrCode: Integer; begin if not Assigned(AIocpRecord) then begin New(AIocpRecord); AIocpRecord.WsaBuf.buf := @FIocpRecvBuf; AIocpRecord.WsaBuf.len := MAX_IOCPBUFSIZE; FIocpRecv := AIocpRecord; end; AIocpRecord.Overlapped.Internal := 0; AIocpRecord.Overlapped.InternalHigh := 0; AIocpRecord.Overlapped.Offset := 0; AIocpRecord.Overlapped.OffsetHigh := 0; AIocpRecord.Overlapped.hEvent := 0; AIocpRecord.IocpOperate := ioRead; iFlags := 0; if WSARecv(FSocket, @AIocpRecord.WsaBuf, 1, iTransfer, iFlags, @AIocpRecord.Overlapped, nil) = SOCKET_ERROR then begin iErrCode := WSAGetLastError; if iErrCode = WSAECONNRESET then //客户端被关闭 FConnected := False; if iErrCode <> ERROR_IO_PENDING then //不抛出异常,触发异常事件 begin FIocpServer.DoError('WSARecv', GetLastWsaErrorStr); ProcessNetError(iErrCode); end; end; end;
WSARecv会返回错误,可以帮助我们定位网络问题,如连接断了,具体函数代码如下:procedure TSocketHandle.ProcessNetError(const AErrorCode: Integer);