TcpClient.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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.Threading;
  32. using System.Text;
  33. using System.Runtime.Serialization.Formatters.Binary;
  34. namespace OpenSim.ApplicationPlugins.LoadBalancer {
  35. public class AsynchronousClient {
  36. private static ManualResetEvent connectDone = new ManualResetEvent(false);
  37. private static ManualResetEvent sendDone = new ManualResetEvent(false);
  38. public static Socket StartClient(string hostname, int port) {
  39. try {
  40. IPHostEntry ipHostInfo = Dns.GetHostEntry(hostname);
  41. IPAddress ipAddress = ipHostInfo.AddressList[0];
  42. IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
  43. Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  44. client.BeginConnect( remoteEP, new AsyncCallback(ConnectCallback), client);
  45. connectDone.WaitOne();
  46. /*
  47. Send(client,"This is a test<EOF>");
  48. sendDone.WaitOne();
  49. Receive(client);
  50. receiveDone.WaitOne();
  51. client.Shutdown(SocketShutdown.Both);
  52. client.Close();
  53. */
  54. return client;
  55. } catch (Exception e) {
  56. Console.WriteLine(e.ToString());
  57. throw new Exception("socket error !!");
  58. }
  59. }
  60. private static void ConnectCallback(IAsyncResult ar) {
  61. try {
  62. Socket client = (Socket) ar.AsyncState;
  63. client.EndConnect(ar);
  64. Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString());
  65. connectDone.Set();
  66. } catch (Exception e) {
  67. Console.WriteLine(e.ToString());
  68. }
  69. }
  70. /*
  71. public static void Receive(Socket client) {
  72. try {
  73. StateObject state = new StateObject();
  74. state.workSocket = client;
  75. client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
  76. } catch (Exception e) {
  77. Console.WriteLine(e.ToString());
  78. }
  79. }
  80. private static void ReceiveCallback( IAsyncResult ar ) {
  81. try {
  82. StateObject state = (StateObject) ar.AsyncState;
  83. Socket client = state.workSocket;
  84. int bytesRead = client.EndReceive(ar);
  85. if (bytesRead > 0) {
  86. state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
  87. client.BeginReceive(state.buffer,0,StateObject.BufferSize,0, new AsyncCallback(ReceiveCallback), state);
  88. } else {
  89. if (state.sb.Length > 1) {
  90. response = state.sb.ToString();
  91. }
  92. receiveDone.Set();
  93. }
  94. } catch (Exception e) {
  95. Console.WriteLine(e.ToString());
  96. }
  97. }
  98. */
  99. public static void Send(Socket client, byte[] byteData) {
  100. client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
  101. }
  102. private static void SendCallback(IAsyncResult ar) {
  103. try {
  104. Socket client = (Socket) ar.AsyncState;
  105. int bytesSent = client.EndSend(ar);
  106. if(bytesSent > 0)
  107. {
  108. //Console.WriteLine("Sent {0} bytes to server.", bytesSent);
  109. }
  110. sendDone.Set();
  111. } catch (Exception e) {
  112. Console.WriteLine(e.ToString());
  113. }
  114. }
  115. }
  116. public class InternalPacketHeader
  117. {
  118. private byte[] buffer = new byte[32];
  119. public int type;
  120. public int throttlePacketType;
  121. public int numbytes;
  122. public Guid agent_id;
  123. public int region_port;
  124. public void FromBytes(byte[] bytes)
  125. {
  126. int i = 0; // offset
  127. try
  128. {
  129. this.type = (int)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24));
  130. this.throttlePacketType = (int)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24));
  131. this.numbytes = (int)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24));
  132. this.agent_id = new Guid(
  133. bytes[i++] | (bytes[i++] << 8) | (bytes[i++] << 16) | bytes[i++] << 24,
  134. (short)(bytes[i++] | (bytes[i++] << 8)),
  135. (short)(bytes[i++] | (bytes[i++] << 8)),
  136. bytes[i++], bytes[i++], bytes[i++], bytes[i++],
  137. bytes[i++], bytes[i++], bytes[i++], bytes[i++]);
  138. this.region_port = (int)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24));
  139. }
  140. catch (Exception)
  141. {
  142. throw new Exception("bad format!!!");
  143. }
  144. }
  145. public byte[] ToBytes()
  146. {
  147. int i = 0;
  148. this.buffer[i++] = (byte)(this.type % 256);
  149. this.buffer[i++] = (byte)((this.type >> 8) % 256);
  150. this.buffer[i++] = (byte)((this.type >> 16) % 256);
  151. this.buffer[i++] = (byte)((this.type >> 24) % 256);
  152. this.buffer[i++] = (byte)(this.throttlePacketType % 256);
  153. this.buffer[i++] = (byte)((this.throttlePacketType >> 8) % 256);
  154. this.buffer[i++] = (byte)((this.throttlePacketType >> 16) % 256);
  155. this.buffer[i++] = (byte)((this.throttlePacketType >> 24) % 256);
  156. this.buffer[i++] = (byte)(this.numbytes % 256);
  157. this.buffer[i++] = (byte)((this.numbytes >> 8) % 256);
  158. this.buffer[i++] = (byte)((this.numbytes >> 16) % 256);
  159. this.buffer[i++] = (byte)((this.numbytes >> 24) % 256);
  160. // no endian care
  161. Buffer.BlockCopy(agent_id.ToByteArray(), 0, this.buffer, i, 16); i += 16;
  162. this.buffer[i++] = (byte)(this.region_port % 256);
  163. this.buffer[i++] = (byte)((this.region_port >> 8) % 256);
  164. this.buffer[i++] = (byte)((this.region_port >> 16) % 256);
  165. this.buffer[i++] = (byte)((this.region_port >> 24) % 256);
  166. return this.buffer;
  167. }
  168. }
  169. public class TcpClient {
  170. public static int internalPacketHeaderSize = 4*4 + 16*1;
  171. private string mHostname;
  172. private int mPort;
  173. private Socket mConnection;
  174. public TcpClient(string hostname, int port) {
  175. this.mHostname = hostname;
  176. this.mPort = port;
  177. this.mConnection = null;
  178. }
  179. public void connect() {
  180. this.mConnection = AsynchronousClient.StartClient(mHostname, mPort);
  181. }
  182. /*
  183. public void recevie() {
  184. if (mConnection == null) {
  185. throw new Exception("client not initialized");
  186. }
  187. try
  188. {
  189. AsynchronousClient.Receive(this.mConnection);
  190. }
  191. catch (Exception e)
  192. {
  193. Console.WriteLine(e.ToString());
  194. mConnection = null;
  195. }
  196. }
  197. */
  198. public void send(InternalPacketHeader header, byte[] packet) {
  199. lock (this)
  200. {
  201. if (mConnection == null) {
  202. // throw new Exception("client not initialized");
  203. connect();
  204. }
  205. AsynchronousClient.Send(this.mConnection, header.ToBytes());
  206. /*
  207. for (int i = 0; i < 10; i++)
  208. {
  209. Console.Write(packet[i] + " ");
  210. }
  211. Console.WriteLine("");
  212. */
  213. AsynchronousClient.Send(this.mConnection, packet);
  214. }
  215. }
  216. }
  217. }