当前位置: 首页 > 工具软件 > Chilkat > 使用案例 >

Chilkat包Socket使用方法...

施彬彬
2023-12-01

打开 Visual Studio Professional 2019 NuGet包管理器

搜索“ChilkatDnCore” 版本:9.5.0.88 (当前最新版2021/12/03)

新建程序:目标框架 .Net Core 3.1

Socket Svr = new Socket();

bool unlockComponent = Svr.UnlockComponent("Int775.CBXXXXX_xxxxxxxxxx3Y"); // 输入激活码(未激活可体验30天)
if (unlockComponent != true)
{
  // 解锁失败打印失败信息
  Console.WriteLine(Svr.LastErrorXml);
  return;
}

try
{
  // true/false启用传输加密
  if (tls) 
  {
    Cert cert = new Cert();
    var loadpfx = cert.LoadPfxFile(@"Keys\证书.pfx", "证书密码"); // 加载证书
    if (!loadpfx || !Svr.InitSslServer(cert))
    {
      Console.WriteLine("LoadPfxFile或InitSslServer失败...");
      Console.WriteLine(Svr.LastErrorXml);
      return;
    }
  }

  if (!Svr.BindAndListen(port, 25)) // 设置监听端口(排队数值25)
  {
    Console.WriteLine($"->监听失败{Svr.LocalIpAddress}:{port}...");
    Console.WriteLine(Svr.LastErrorXml);
    return;
  }
  else
  {
    Console.WriteLine($"->监听成功{Svr.LocalIpAddress}:{Svr.LocalPort}->SSL:{tls}");
    Svr.MaxReadIdleMs = 500;
    Svr.MaxSendIdleMs = 500;
    ThreadPool.QueueUserWorkItem(Accept, Svr);
  }
}
catch (Exception ex)
{
  Console.WriteLine($"->BindAndListen错误{Svr.LocalIpAddress}:{Svr.LocalPort}->{ex.Message}...");
}        
private void Accept(object st)
{
  Chilkat.Socket s = st as Socket;
  while (s != null)
  {
    try
    {
      Socket c = s.AcceptNextConnection(1500);   
      if (c != null && c.LastMethodSuccess)
      {                                                         
        _ = ThreadPool.QueueUserWorkItem(OnRecive, c);
      }
    }
    catch { Console.WriteLine($"->AcceptNextConnection->Catch..."); }
  }
}
/// <summary>
/// 接收消息
/// </summary>
private void OnRecive(object cSocket)
{                      
  Chilkat.Socket s = cSocket as Chilkat.Socket;
  // 设置接收|发送Packet大小
  s.SendPacketSize = 8192;
  s.ReceivePacketSize = 8192;      
  while (true)
  {
    try
    {
      byte[] r = s.ReceiveBytes();
      int rlen = r.Length;
      if (s == null || !s.IsConnected || rlen <= 0 || rlen > 8096) { break; }
      // 自定义数据包最长8096包头12
      if (rlen >= 12 && rlen <= 8096) // 
      {                         
         // 拆包    
         PacketX.UnPack(s, r, rlen);
      }
    }
    catch (Exception ex)
    {
       Console.WriteLine($"->OnReciveCatch->{ex}"); break;
    }
 }
 if (s != null)
 {
   ClientOffline(s.ObjectId); 
   if (s.IsConnected) { s.Close(1000); }  s.Dispose();
 }
 GC.Collect();         
}

ps:UnlockComponent(激活码)有偿提供...

 类似资料: