WebSocketEchoModule.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Reflection;
  30. using OpenSim.Framework.Servers;
  31. using Mono.Addins;
  32. using log4net;
  33. using Nini.Config;
  34. using OpenSim.Region.Framework.Interfaces;
  35. using OpenSim.Region.Framework.Scenes;
  36. using OpenSim.Framework.Servers.HttpServer;
  37. namespace OpenSim.Region.OptionalModules.WebSocketEchoModule
  38. {
  39. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WebSocketEchoModule")]
  40. public class WebSocketEchoModule : ISharedRegionModule
  41. {
  42. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. private bool enabled;
  44. public string Name { get { return "WebSocketEchoModule"; } }
  45. public Type ReplaceableInterface { get { return null; } }
  46. private HashSet<WebSocketHttpServerHandler> _activeHandlers = new HashSet<WebSocketHttpServerHandler>();
  47. public void Initialise(IConfigSource pConfig)
  48. {
  49. enabled = (pConfig.Configs["WebSocketEcho"] != null);
  50. // if (enabled)
  51. // m_log.DebugFormat("[WebSocketEchoModule]: INITIALIZED MODULE");
  52. }
  53. /// <summary>
  54. /// This method sets up the callback to WebSocketHandlerCallback below when a HTTPRequest comes in for /echo
  55. /// </summary>
  56. public void PostInitialise()
  57. {
  58. if (enabled)
  59. MainServer.Instance.AddWebSocketHandler("/echo", WebSocketHandlerCallback);
  60. }
  61. // This gets called by BaseHttpServer and gives us an opportunity to set things on the WebSocket handler before we turn it on
  62. public void WebSocketHandlerCallback(string path, WebSocketHttpServerHandler handler)
  63. {
  64. SubscribeToEvents(handler);
  65. handler.SetChunksize(8192);
  66. handler.NoDelay_TCP_Nagle = true;
  67. handler.HandshakeAndUpgrade();
  68. }
  69. //These are our normal events
  70. public void SubscribeToEvents(WebSocketHttpServerHandler handler)
  71. {
  72. handler.OnClose += HandlerOnOnClose;
  73. handler.OnText += HandlerOnOnText;
  74. handler.OnUpgradeCompleted += HandlerOnOnUpgradeCompleted;
  75. handler.OnData += HandlerOnOnData;
  76. handler.OnPong += HandlerOnOnPong;
  77. }
  78. public void UnSubscribeToEvents(WebSocketHttpServerHandler handler)
  79. {
  80. handler.OnClose -= HandlerOnOnClose;
  81. handler.OnText -= HandlerOnOnText;
  82. handler.OnUpgradeCompleted -= HandlerOnOnUpgradeCompleted;
  83. handler.OnData -= HandlerOnOnData;
  84. handler.OnPong -= HandlerOnOnPong;
  85. }
  86. private void HandlerOnOnPong(object sender, PongEventArgs pongdata)
  87. {
  88. m_log.Info("[WebSocketEchoModule]: Got a pong.. ping time: " + pongdata.PingResponseMS);
  89. }
  90. private void HandlerOnOnData(object sender, WebsocketDataEventArgs data)
  91. {
  92. WebSocketHttpServerHandler obj = sender as WebSocketHttpServerHandler;
  93. obj.SendData(data.Data);
  94. m_log.Info("[WebSocketEchoModule]: We received a bunch of ugly non-printable bytes");
  95. obj.SendPingCheck();
  96. }
  97. private void HandlerOnOnUpgradeCompleted(object sender, UpgradeCompletedEventArgs completeddata)
  98. {
  99. WebSocketHttpServerHandler obj = sender as WebSocketHttpServerHandler;
  100. _activeHandlers.Add(obj);
  101. }
  102. private void HandlerOnOnText(object sender, WebsocketTextEventArgs text)
  103. {
  104. WebSocketHttpServerHandler obj = sender as WebSocketHttpServerHandler;
  105. obj.SendMessage(text.Data);
  106. m_log.Info("[WebSocketEchoModule]: We received this: " + text.Data);
  107. }
  108. // Remove the references to our handler
  109. private void HandlerOnOnClose(object sender, CloseEventArgs closedata)
  110. {
  111. WebSocketHttpServerHandler obj = sender as WebSocketHttpServerHandler;
  112. UnSubscribeToEvents(obj);
  113. lock (_activeHandlers)
  114. _activeHandlers.Remove(obj);
  115. obj.Dispose();
  116. }
  117. // Shutting down.. so shut down all sockets.
  118. // Note.. this should be done outside of an ienumerable if you're also hook to the close event.
  119. public void Close()
  120. {
  121. if (!enabled)
  122. return;
  123. // We convert this to a for loop so we're not in in an IEnumerable when the close
  124. //call triggers an event which then removes item from _activeHandlers that we're enumerating
  125. WebSocketHttpServerHandler[] items = new WebSocketHttpServerHandler[_activeHandlers.Count];
  126. _activeHandlers.CopyTo(items);
  127. for (int i = 0; i < items.Length; i++)
  128. {
  129. items[i].Close(string.Empty);
  130. items[i].Dispose();
  131. }
  132. _activeHandlers.Clear();
  133. MainServer.Instance.RemoveWebSocketHandler("/echo");
  134. }
  135. public void AddRegion(Scene scene)
  136. {
  137. // m_log.DebugFormat("[WebSocketEchoModule]: REGION {0} ADDED", scene.RegionInfo.RegionName);
  138. }
  139. public void RemoveRegion(Scene scene)
  140. {
  141. // m_log.DebugFormat("[WebSocketEchoModule]: REGION {0} REMOVED", scene.RegionInfo.RegionName);
  142. }
  143. public void RegionLoaded(Scene scene)
  144. {
  145. // m_log.DebugFormat("[WebSocketEchoModule]: REGION {0} LOADED", scene.RegionInfo.RegionName);
  146. }
  147. }
  148. }