UChannel.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Base
  5. {
  6. internal class UChannel: AChannel
  7. {
  8. private readonly USocket socket;
  9. private readonly string remoteAddress;
  10. public UChannel(USocket socket, string host, int port, UService service): base(service)
  11. {
  12. this.socket = socket;
  13. this.service = service;
  14. this.remoteAddress = host + ":" + port;
  15. }
  16. public UChannel(USocket socket, UService service) : base(service)
  17. {
  18. this.socket = socket;
  19. this.service = service;
  20. this.remoteAddress = socket.RemoteAddress;
  21. }
  22. public override void Dispose()
  23. {
  24. if (this.Id == 0)
  25. {
  26. return;
  27. }
  28. base.Dispose();
  29. this.socket.Dispose();
  30. }
  31. public string RemoteAddress
  32. {
  33. get
  34. {
  35. return this.remoteAddress;
  36. }
  37. }
  38. public override void ConnectAsync()
  39. {
  40. string[] ss = this.remoteAddress.Split(':');
  41. ushort port = ushort.Parse(ss[1]);
  42. this.socket.ConnectAsync(ss[0], port);
  43. }
  44. public override void Send(byte[] buffer, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
  45. {
  46. this.socket.SendAsync(buffer, channelID, flags);
  47. }
  48. public override void Send(List<byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
  49. {
  50. int size = buffers.Select(b => b.Length).Sum();
  51. var buffer = new byte[size];
  52. int index = 0;
  53. foreach (byte[] bytes in buffers)
  54. {
  55. Array.Copy(bytes, 0, buffer, index, bytes.Length);
  56. index += bytes.Length;
  57. }
  58. this.socket.SendAsync(buffer, channelID, flags);
  59. }
  60. public override byte[] Recv()
  61. {
  62. if (this.socket?.RecvQueue.Count == 0)
  63. {
  64. return null;
  65. }
  66. return this.socket?.RecvQueue.Dequeue();
  67. }
  68. }
  69. }