ChatServer.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Collections.Generic;
  6. using NetCoreServer;
  7. namespace websocketserver.Library
  8. {
  9. class ChatServer : WsServer
  10. {
  11. List<UserSession> users;
  12. public ChatServer(IPAddress address, int port) : base(address, port)
  13. {
  14. users = new List<UserSession>();
  15. }
  16. protected override TcpSession CreateSession()
  17. {
  18. UserSession user = new UserSession(this);
  19. users.Add(user);
  20. return user;
  21. }
  22. public void Subscribe(string key, UserSession session)
  23. {
  24. if (session.GetUserKey() == "")
  25. {
  26. return;
  27. }
  28. GetUsersInChannel(session).ForEach(s => s.SendTextAsync("leave " + session.GetUserKey()));
  29. session.SetChannel(key);
  30. var newChannelUsers = GetUsersInChannel(session);
  31. newChannelUsers.ForEach(s => s.SendTextAsync("join " + session.GetUserKey() + " " + session.GetPosition().X + " " + session.GetPosition().Y));
  32. session.SendTextAsync("population " + string.Join(" ", newChannelUsers.Select(u => u.GetUserKey() + " " + u.GetPosition().X + " " + u.GetPosition().Y)));
  33. }
  34. public void Move(UserSession session)
  35. {
  36. if (session.GetUserKey() == "")
  37. {
  38. return;
  39. }
  40. GetUsersInChannel(session).ForEach(s => s.SendTextAsync("move " + session.GetUserKey() + " " + session.GetPosition().X + " " + session.GetPosition().Y));
  41. }
  42. public void Chat(UserSession session, string message)
  43. {
  44. if (session.GetUserKey() == "" || message == "")
  45. {
  46. return;
  47. }
  48. Console.WriteLine("{0} [{1}]: {2}", session.GetUserKey(), session.GetChannel(), message);
  49. GetUsersInChannel(session).ForEach(s => s.SendTextAsync("chat " + session.GetUserKey() + " " + message));
  50. }
  51. public void Disconnect(UserSession session)
  52. {
  53. GetUsersInChannel(session).ForEach(s => s.SendTextAsync("leave " + session.GetUserKey()));
  54. users.Remove(session);
  55. }
  56. public List<UserSession> GetUsersInChannel(UserSession session)
  57. {
  58. return users.FindAll(u => u.GetUserKey() != "" && u.GetUserKey() != session.GetUserKey() && u.GetChannel() == session.GetChannel());
  59. }
  60. public List<UserSession> GetUsersInChannel(string key)
  61. {
  62. return users.FindAll(u => u.GetUserKey() != "" && u.GetChannel() == key);
  63. }
  64. protected override void OnError(SocketError error)
  65. {
  66. Console.WriteLine($"Chat WebSocket server caught an error with code {error}");
  67. }
  68. }
  69. }