DeliveryClient.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.IO.Pipes;
  3. using System.Net.Sockets;
  4. using Sers.Core.CL.MessageDelivery;
  5. using Vit.Core.Module.Log;
  6. namespace Sers.CL.Ipc.NamedPipe
  7. {
  8. public class DeliveryClient: IDeliveryClient
  9. {
  10. DeliveryConnection _conn = new DeliveryConnection();
  11. public IDeliveryConnection conn => _conn;
  12. /// <summary>
  13. /// 请勿处理耗时操作,需立即返回。接收到客户端的数据事件
  14. /// </summary>
  15. public Action<IDeliveryConnection, ArraySegment<byte>> Conn_OnGetFrame { set { _conn.OnGetFrame = value; } }
  16. public Action<IDeliveryConnection> Conn_OnDisconnected { set=> _conn.Conn_OnDisconnected=value; }
  17. public string serverName = ".";
  18. public string pipeName = "demo";
  19. string connKey;
  20. public bool Connect()
  21. {
  22. Logger.Info("[CL.DeliveryClient] Socket.ThreadWait,connecting... serverName:" + serverName + " pipeName:" + pipeName);
  23. try
  24. {
  25. connKey=ConnectionKeyHelp.Subscribe(pipeName, serverName);
  26. }
  27. catch (Exception ex)
  28. {
  29. //服务启动失败
  30. Logger.Error("[CL.DeliveryClient] Socket.ThreadWait,connect - Error", ex);
  31. return false;
  32. }
  33. NamedPipeClientStream client = new NamedPipeClientStream(serverName, pipeName + "." + connKey, PipeDirection.InOut, PipeOptions.Asynchronous);
  34. //var task=client.ConnectAsync();
  35. //task.Wait(10000);
  36. //if (!task.IsCompleted)
  37. //{
  38. // return false;
  39. //}
  40. client.Connect(10000);
  41. if (!client.IsConnected)
  42. {
  43. return false;
  44. }
  45. Logger.Info("[Ipc]客户端已创建,connKey:" + connKey);
  46. _conn.Init(client);
  47. _conn.StartBackThreadToReceiveMsg();
  48. Logger.Info("[CL.DeliveryClient] Socket.ThreadWait,connected.");
  49. return true;
  50. }
  51. /// Disconnect from the host.
  52. public void Close()
  53. {
  54. try
  55. {
  56. _conn?.Close();
  57. }
  58. catch (Exception ex)
  59. {
  60. Logger.Error(ex);
  61. }
  62. _conn = null;
  63. }
  64. }
  65. }