Advertisement
Nucleo

Untitled

Sep 18th, 2011
351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.99 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading;
  6. using System.IO;
  7. using System.Collections;
  8. using System.Collections.Generic;
  9.  
  10. // State object for reading client data asynchronously
  11. public class StateObject
  12. {
  13. // Client socket.
  14. public Socket workSocket = null;
  15. // Size of receive buffer.
  16. public const int BufferSize = 1024;
  17. // Receive buffer.
  18. public byte[] buffer = new byte[BufferSize];
  19. // Received data string.
  20. public StringBuilder sb = new StringBuilder();
  21.  
  22. public string command;
  23. public int userID;
  24. public int SystemID;
  25. public decimal xfrom;
  26. public decimal yfrom;
  27. public decimal xto;
  28. public decimal yto;
  29. public string UserName;
  30. public string ShipName;
  31.  
  32. }
  33.  
  34.  
  35.  
  36. public class AsynchronousSocketListener
  37. {
  38. public static ArrayList Clients = new ArrayList();
  39.  
  40. // Thread signal.
  41. public static ManualResetEvent allDone = new ManualResetEvent(false);
  42.  
  43. public AsynchronousSocketListener()
  44.  
  45. {
  46.  
  47. }
  48.  
  49. public static bool IsConnected(Socket socket)
  50. {
  51. try
  52. {
  53. return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
  54. }
  55. catch (SocketException) { return false; }
  56. }
  57.  
  58.  
  59. public static void StartListening()
  60. {
  61. // Data buffer for incoming data.
  62. byte[] bytes = new Byte[1024];
  63.  
  64. // Establish the local endpoint for the socket.
  65. // The DNS name of the computer
  66. // running the listener is "host.contoso.com".
  67. IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
  68. IPAddress ipAddress = ipHostInfo.AddressList[0];
  69. IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 4444);
  70.  
  71. // Create a TCP/IP socket.
  72. Socket listener = new Socket(AddressFamily.InterNetwork,
  73. SocketType.Stream, ProtocolType.Tcp);
  74.  
  75. // Bind the socket to the local endpoint and listen for incoming connections.
  76. try
  77. {
  78. listener.Bind(localEndPoint);
  79. listener.Listen(100);
  80.  
  81.  
  82. while (true)
  83. {
  84. // Set the event to nonsignaled state.
  85. allDone.Reset();
  86.  
  87. // Start an asynchronous socket to listen for connections.
  88. //Console.WriteLine("Socket Server Started");
  89.  
  90.  
  91. listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
  92.  
  93.  
  94.  
  95. // Wait until a connection is made before continuing.
  96. allDone.WaitOne();
  97.  
  98.  
  99. }
  100.  
  101. }
  102. catch (Exception e)
  103. {
  104. Console.WriteLine(e.ToString());
  105. }
  106.  
  107. Console.WriteLine("\nPress ENTER to continue...");
  108. Console.Read();
  109.  
  110. }
  111.  
  112. public static void AcceptCallback(IAsyncResult ar)
  113. {
  114. // Signal the main thread to continue.
  115. allDone.Set();
  116.  
  117. // Get the socket that handles the client request.
  118. Socket listener = (Socket)ar.AsyncState;
  119. Socket handler = listener.EndAccept(ar);
  120.  
  121. StateObject client = new StateObject();
  122.  
  123. int i = Clients.Add(client);
  124. //Console.WriteLine("Client " + i.ToString() + " Connected" );
  125.  
  126.  
  127. client.workSocket = handler;
  128. handler.BeginReceive(client.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), client);
  129.  
  130.  
  131.  
  132. }
  133.  
  134. public static void ReadCallback(IAsyncResult ar)
  135. {
  136. String content = String.Empty;
  137.  
  138. // Retrieve the state object and the handler socket
  139. // from the asynchronous state object.
  140. StateObject state = (StateObject)ar.AsyncState;
  141. Socket handler = state.workSocket;
  142.  
  143. // Read data from the client socket.
  144. int bytesRead = handler.EndReceive(ar);
  145.  
  146.  
  147.  
  148. if (bytesRead > 0)
  149. {
  150. // There might be more data, so store the data received so far.
  151. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
  152.  
  153. // Check for end-of-file tag. If it is not there, read
  154. // more data.
  155. content = state.sb.ToString();
  156.  
  157. if (content.IndexOf("<EOF>") > -1)
  158. {
  159. Console.WriteLine("Data Received : " + content.ToString());
  160. string[] Data;
  161. string Message = "";
  162. Data = content.Split('|');
  163.  
  164. if (Data[0] == "0000")
  165. {
  166.  
  167. state.userID = Convert.ToInt32(Data[1]);
  168. state.SystemID = Convert.ToInt32(Data[2]);
  169. state.xfrom = Convert.ToDecimal(Data[3]);
  170. state.yfrom = Convert.ToDecimal(Data[4]);
  171. state.xto = Convert.ToDecimal(Data[5]);
  172. state.yto = Convert.ToDecimal(Data[6]);
  173. state.UserName = Data[7];
  174. state.ShipName = Data[8];
  175.  
  176. foreach (StateObject client in Clients)
  177. {
  178. if (client.SystemID == state.SystemID && client.userID != state.userID)
  179. {
  180.  
  181. Message = "0001|" + state.userID.ToString() + "|" + state.xfrom.ToString() + "|" + state.yfrom.ToString() + "|" + state.xto.ToString() + "|" + state.yto.ToString() + "|" + state.UserName.ToString() + "|" + state.ShipName.ToString();
  182.  
  183. Send(client.workSocket, Message);
  184. Console.WriteLine("Data Sent to : " + client.userID.ToString() + " Message : " + Message.ToString());
  185.  
  186. Message = "0001|" + client.userID.ToString() + "|" + client.xfrom.ToString() + "|" + client.yfrom.ToString() + "|" + client.xto.ToString() + "|" + client.yto.ToString() + "|" + client.UserName.ToString() + "|" + client.ShipName.ToString();
  187. Send(state.workSocket, Message);
  188. Console.WriteLine("Data Sent to : " + state.userID.ToString() + " Message : " + Message.ToString());
  189.  
  190.  
  191. }
  192.  
  193. }
  194. }
  195.  
  196. // All the data has been read from the
  197. // client. Display it on the console.
  198. // Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
  199. // Echo the data back to the client.
  200. //handler.Close();
  201. }
  202. else
  203. {
  204.  
  205. // Not all data received. Get more.
  206. handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  207. new AsyncCallback(ReadCallback), state);
  208. }
  209. }
  210. }
  211.  
  212. private static void Send(Socket handler, string data)
  213. {
  214. try
  215. {
  216. // Convert the string data to byte data using ASCII encoding.
  217. byte[] byteData = Encoding.ASCII.GetBytes(data);
  218.  
  219. // Begin sending the data to the remote device.
  220. handler.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);
  221. }
  222. catch (Exception e)
  223. {
  224.  
  225. Console.WriteLine("Couldn't Send Data to Socket");
  226.  
  227.  
  228. }
  229.  
  230. }
  231.  
  232. private static void SendCallback(IAsyncResult ar)
  233. {
  234. try
  235. {
  236.  
  237. // Retrieve the socket from the state object.
  238. Socket handler = (Socket)ar.AsyncState;
  239.  
  240.  
  241. // Complete sending the data to the remote device.
  242. int bytesSent = handler.EndSend(ar);
  243. //Console.WriteLine("Sent {0} bytes to client.", bytesSent);
  244.  
  245.  
  246.  
  247.  
  248. }
  249. catch (Exception e)
  250. {
  251.  
  252. Console.WriteLine(e.ToString());
  253.  
  254. }
  255. }
  256.  
  257.  
  258. #region policyserver
  259. private static TcpListener tcl;
  260. //Generate policy
  261. private static string response = "<?xml version=\"1.0\"?> "+
  262. "<!DOCTYPE cross-domain-policy SYSTEM "+
  263. " \"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\"> "+
  264. "<cross-domain-policy>"+
  265. " <allow-access-from domain=\"*\" to-ports=\"4444\"/>"+
  266. "</cross-domain-policy>\0";
  267. private static void AcceptCallback1(IAsyncResult ar)
  268. {
  269. try
  270. {
  271. TcpListener listener = null;
  272. Socket client = null;
  273.  
  274. listener = (TcpListener)ar.AsyncState;
  275. client = listener.EndAcceptSocket(ar);
  276. NetworkStream ns = new NetworkStream(client);
  277. StreamReader sr = new StreamReader(ns);
  278. StreamWriter sw = new StreamWriter(ns);
  279. Console.WriteLine("Sent Policy File...");
  280.  
  281. sr.Read();
  282. //Send policy
  283. sw.Write(response);
  284. sw.Flush();
  285. ns.Flush();
  286. //Cleanup
  287. sw.Close();
  288. sr.Close();
  289. ns.Close();
  290. client.Close();
  291. //Do it again!
  292. tcl.BeginAcceptSocket(new AsyncCallback(AcceptCallback1), tcl);
  293. }
  294. catch (Exception e)
  295. {
  296. Console.WriteLine(e.Message);
  297. return;
  298. }
  299. }
  300.  
  301. static void RunPolicyServer()
  302. {
  303. Console.WriteLine("Policy Server Running");
  304.  
  305. tcl = new TcpListener(IPAddress.Any, 843);
  306. tcl.Start();
  307. tcl.BeginAcceptSocket(new AsyncCallback(AcceptCallback1), tcl);
  308.  
  309. //Console.ReadLine();
  310. }
  311.  
  312.  
  313. #endregion
  314.  
  315. public static int Main(String[] args)
  316. {
  317.  
  318.  
  319. Thread PolicyServer = new Thread(RunPolicyServer);
  320. PolicyServer.Start();
  321.  
  322. StartListening();
  323. return 0;
  324. }
  325. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement