Advertisement
Nucleo

Untitled

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