zoukankan      html  css  js  c++  java
  • SOCKET缓存

    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.
    

      

  • 相关阅读:
    MFC中L, _T(),TEXT,_TEXT区别以及含义
    Qt5完美解决 界面显示中文乱码
    TCP三次握手四次挥手详解
    TCP 长连接与短连接的区别
    Servlet 生命周期、工作原理
    Java反射的三种实现方式
    apache httpclient 4.5 兼容 http https
    mysql千万级大数据SQL查询优化
    Java String字符串补0或空格
    mysql存储过程
  • 原文地址:https://www.cnblogs.com/hnxxcxg/p/13296359.html
Copyright © 2011-2022 走看看