UserSession.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using NetCoreServer;
  2. using System.Drawing;
  3. using System;
  4. using System.Text;
  5. using System.Linq;
  6. using System.Collections.Generic;
  7. using System.Net.Sockets;
  8. namespace websocketserver.Library
  9. {
  10. class UserSession : WsSession
  11. {
  12. private ChatServer server;
  13. private string channelKey;
  14. private string userKey;
  15. private string roomKey;
  16. private PointF position;
  17. public UserSession(ChatServer server) : base(server)
  18. {
  19. this.server = server;
  20. this.channelKey = "room-0,0";
  21. this.userKey = "";
  22. this.roomKey = "room-0,0";
  23. this.position = new PointF(0.5F, 0.5F);
  24. }
  25. public string GetChannel()
  26. {
  27. return this.channelKey;
  28. }
  29. public void SetChannel(string key)
  30. {
  31. this.channelKey = key;
  32. }
  33. public PointF GetPosition()
  34. {
  35. return this.position;
  36. }
  37. public string GetUserKey()
  38. {
  39. return this.userKey;
  40. }
  41. public string GetRoomKey()
  42. {
  43. return this.roomKey;
  44. }
  45. public override void OnWsConnected(HttpRequest request)
  46. {
  47. Console.WriteLine($"Chat WebSocket session with Id {Id} connected!");
  48. // string message = "connected";
  49. // SendTextAsync(message);
  50. }
  51. public override void OnWsDisconnected()
  52. {
  53. Console.WriteLine("User {0} disconnected", this.GetUserKey());
  54. this.server.Disconnect(this);
  55. }
  56. public override void OnWsReceived(byte[] buffer, long offset, long size)
  57. {
  58. string message = Encoding.UTF8.GetString(buffer, (int)offset, (int)size);
  59. string[] splitMessage = message.Split(" ");
  60. string command = splitMessage[0];
  61. switch (command)
  62. {
  63. case "subscribe":
  64. this.userKey = splitMessage[1];
  65. this.roomKey = splitMessage[2];
  66. Console.WriteLine("User {0} joining {1}", this.GetUserKey(), this.GetRoomKey());
  67. this.server.Subscribe(this.roomKey, this);
  68. break;
  69. case "move":
  70. this.userKey = splitMessage[1];
  71. this.position.X = float.Parse(splitMessage[2]);
  72. this.position.Y = float.Parse(splitMessage[3]);
  73. this.server.Move(this);
  74. break;
  75. case "chat":
  76. this.server.Chat(this, string.Join(" ", splitMessage.Skip(1).ToArray()));
  77. break;
  78. case "quit":
  79. Close(1000);
  80. break;
  81. default:
  82. Console.WriteLine("Incoming: {0}", message);
  83. this.server.MulticastText(message);
  84. break;
  85. }
  86. }
  87. protected override void OnError(SocketError error)
  88. {
  89. Console.WriteLine($"Chat WebSocket session caught an error with code {error}");
  90. }
  91. }
  92. }