首页 > 其他 > 详细

SOCKET缓存

时间:2020-07-13 23:39:21      阅读:53      评论:0      收藏:0      [点我收藏+]

SOCKET缓存

/// <author>cxg 2020-7-13</author>
/// socket缓存(线程安全)

unit sockBuf;

interface

uses
  System.SyncObjs, Net.SocketAPI, Net.CrossSocket.Base, Net.CrossSocket,
  System.Generics.Collections, System.Classes, System.SysUtils;

const
  bufsize = 32768; //32K

type
  TSockBuf = class
  private
    bufs: TDictionary<ICrossConnection, TMemoryStream>; //缓存字典,每个连接都有自己的缓存
    fCS: TCriticalSection;
  public
    constructor Create;
    destructor Destroy; override;
    function process(const Connection: ICrossConnection; const Buf: Pointer; const Len: Integer): TMemoryStream;
    procedure remove(const Connection: ICrossConnection);
  end;

implementation

{ TSockBuf }

constructor TSockBuf.Create;
begin
  bufs := TDictionary<ICrossConnection, TMemoryStream>.Create;
  fCS := TCriticalSection.Create;
end;

destructor TSockBuf.Destroy;
begin
  for var v: TMemoryStream in bufs.Values do
    v.Free;
  FreeAndNil(bufs);
  FreeAndNil(fCS);
  inherited;
end;

function TSockBuf.process(const Connection: ICrossConnection; const Buf: Pointer; const Len: Integer): TMemoryStream;
begin
  fCS.Enter;
  if not bufs.ContainsKey(Connection) then  //新连接
  begin
    Result := TMemoryStream.Create;
    bufs.Add(Connection, Result);
  end
  else     //旧连接
    bufs.TryGetValue(Connection, Result);
  fCS.Leave;
  Result.Write(Buf^, Len);
end;

procedure TSockBuf.remove(const Connection: ICrossConnection);
begin
  fCS.Enter;
  bufs[Connection].Free;
  bufs.Remove(Connection);
  fCS.Leave;
end;

end.

  

SOCKET缓存

原文:https://www.cnblogs.com/hnxxcxg/p/13296359.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!