TcpServer.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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 OpenSim 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.IO;
  29. using System.Net;
  30. using System.Net.Sockets;
  31. using System.Text;
  32. using System.Threading;
  33. using System.Runtime.Serialization.Formatters.Binary;
  34. using OpenSim.Framework.Console;
  35. namespace OpenSim.ApplicationPlugins.LoadBalancer {
  36. public class StateObject {
  37. public Socket workSocket = null;
  38. public const int BufferSize = 2048;
  39. public byte[] buffer = new byte[BufferSize];
  40. public MemoryStream ms_ptr = new MemoryStream();
  41. public InternalPacketHeader header = null;
  42. }
  43. public class AsynchronousSocketListener {
  44. public static string data = null;
  45. public static ManualResetEvent allDone = new ManualResetEvent(false);
  46. #region KIRYU
  47. public delegate void PacketRecieveHandler(InternalPacketHeader header, byte[] buff);
  48. public static PacketRecieveHandler PacketHandler = null;
  49. #endregion
  50. public AsynchronousSocketListener() { }
  51. public static void StartListening(int port) {
  52. IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
  53. IPAddress ipAddress = ipHostInfo.AddressList[0];
  54. IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
  55. Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
  56. try {
  57. listener.Bind(localEndPoint);
  58. listener.Listen(100);
  59. while (true) {
  60. allDone.Reset();
  61. listener.BeginAccept( new AsyncCallback(AcceptCallback), listener );
  62. allDone.WaitOne();
  63. }
  64. } catch (Exception e) {
  65. Console.WriteLine(e.ToString());
  66. }
  67. /*
  68. Console.WriteLine("\nPress ENTER to continue...");
  69. Console.Read();
  70. */
  71. }
  72. public static void AcceptCallback(IAsyncResult ar) {
  73. allDone.Set();
  74. Socket listener = (Socket) ar.AsyncState;
  75. Socket handler = listener.EndAccept(ar);
  76. StateObject state = new StateObject();
  77. state.workSocket = handler;
  78. handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
  79. }
  80. public static void ReadCallback(IAsyncResult ar) {
  81. StateObject state = (StateObject) ar.AsyncState;
  82. Socket handler = state.workSocket;
  83. try
  84. {
  85. int bytesRead = handler.EndReceive(ar);
  86. //MainLog.Instance.Verbose("TCPSERVER", "Received packet [{0}]", bytesRead);
  87. if (bytesRead > 0) {
  88. state.ms_ptr.Write(state.buffer, 0, bytesRead);
  89. }
  90. else
  91. {
  92. //MainLog.Instance.Verbose("TCPSERVER", "Connection terminated");
  93. return;
  94. }
  95. long rest_size = state.ms_ptr.Length;
  96. long current_pos = 0;
  97. while (rest_size > TcpClient.internalPacketHeaderSize) {
  98. if ((state.header == null) && (rest_size >= TcpClient.internalPacketHeaderSize))
  99. {
  100. //MainLog.Instance.Verbose("TCPSERVER", "Processing header");
  101. // reading header
  102. state.header = new InternalPacketHeader();
  103. byte[] headerbytes = new byte[TcpClient.internalPacketHeaderSize];
  104. state.ms_ptr.Position = current_pos;
  105. state.ms_ptr.Read(headerbytes, 0, TcpClient.internalPacketHeaderSize);
  106. state.ms_ptr.Seek(0, SeekOrigin.End);
  107. state.header.FromBytes(headerbytes);
  108. }
  109. if ((state.header != null) && (rest_size >= state.header.numbytes + TcpClient.internalPacketHeaderSize))
  110. {
  111. //MainLog.Instance.Verbose("TCPSERVER", "Processing body");
  112. // reading body
  113. byte[] packet = new byte[state.header.numbytes];
  114. state.ms_ptr.Position = current_pos + TcpClient.internalPacketHeaderSize;
  115. state.ms_ptr.Read(packet, 0, state.header.numbytes);
  116. /*
  117. for(int i=0; i<state.header.numbytes; i++) {
  118. System.Console.Write(packet[i] + " ");
  119. }
  120. System.Console.WriteLine();
  121. */
  122. state.ms_ptr.Seek(0, SeekOrigin.End);
  123. // call loadbarancer function
  124. if (PacketHandler != null)
  125. {
  126. //MainLog.Instance.Verbose("TCPSERVER", "calling PacketHandler");
  127. PacketHandler(state.header, packet);
  128. }
  129. else
  130. {
  131. //MainLog.Instance.Verbose("TCPSERVER", "PacketHandler not found");
  132. }
  133. int read_size = state.header.numbytes + TcpClient.internalPacketHeaderSize;
  134. state.header = null;
  135. rest_size -= read_size;
  136. current_pos += read_size;
  137. if (rest_size < TcpClient.internalPacketHeaderSize) {
  138. byte[] rest_bytes = new byte[rest_size];
  139. state.ms_ptr.Position = read_size;
  140. state.ms_ptr.Read(rest_bytes, 0, (int)rest_size);
  141. state.ms_ptr.Close();
  142. state.ms_ptr = new MemoryStream();
  143. state.ms_ptr.Write(rest_bytes, 0, (int)rest_size);
  144. break;
  145. }
  146. }
  147. } // while (true)
  148. }
  149. catch (Exception)
  150. {
  151. //MainLog.Instance.Verbose("TCPSERVER", e.ToString());
  152. //MainLog.Instance.Verbose("TCPSERVER", e.StackTrace);
  153. }
  154. handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
  155. }
  156. }
  157. public class TcpServer {
  158. private int mPort = 11000;
  159. public TcpServer() {
  160. }
  161. public TcpServer(int port) {
  162. mPort = port;
  163. }
  164. public void start() {
  165. AsynchronousSocketListener.StartListening(mPort);
  166. }
  167. }
  168. }