Guest User

Untitled

a guest
Jan 18th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.31 KB | None | 0 0
  1. private ArrayList m_aryClients = new ArrayList();
  2.  
  3. public void listen()
  4. {
  5. try
  6. {
  7. // Check the port value
  8. if (textBoxPort.Text == "")
  9. {
  10. MessageBox.Show("Please enter a Port Number");
  11. return;
  12. }
  13. string portStr = textBoxPort.Text;
  14.  
  15. try
  16. {
  17. // NOTE: DNS lookups are nice and all but quite time consuming.
  18. strHostName = Dns.GetHostName();
  19. IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
  20. aryLocalAddr = ipEntry.AddressList;
  21. }
  22. catch (Exception ex)
  23. {
  24. Console.WriteLine("Error trying to get local address {0} ", ex.Message);
  25. }
  26.  
  27. // Verify we got an IP address. Tell the user if we did
  28. if (aryLocalAddr == null || aryLocalAddr.Length < 1)
  29. {
  30. Console.WriteLine("Unable to get local address");
  31. return;
  32. }
  33. // Create the listening socket...
  34. m_mainSocket = new Socket(AddressFamily.InterNetwork,
  35. SocketType.Stream,
  36. ProtocolType.Tcp);
  37. IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
  38. // Bind to local IP Address...
  39. m_mainSocket.Bind(ipLocal);
  40. // Start listening...
  41. m_mainSocket.Listen(500);
  42. m_mainSocket.BeginAccept(new AsyncCallback(OnConnectRequest), m_mainSocket);
  43.  
  44.  
  45. UpdateControls(true);
  46.  
  47. }
  48. catch (SocketException se)
  49. {
  50. writer.WriteToLog(se.Message);
  51. }
  52.  
  53. }
  54.  
  55. /// <summary>
  56. /// Callback used when a client requests a connection.
  57. /// Accpet the connection, adding it to our list and setup to
  58. /// accept more connections.
  59. /// </summary>
  60. /// <param name="ar"></param>
  61. public void OnConnectRequest(IAsyncResult ar)
  62. {
  63. Socket listener = (Socket)ar.AsyncState;
  64. try
  65. {
  66. NewConnection(listener.EndAccept(ar));
  67. listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
  68. }
  69. catch (Exception ex)
  70. {
  71. }
  72.  
  73. }
  74.  
  75. /// <summary>
  76. /// Add the given connection to our list of clients
  77. /// Note we have a new friend
  78. /// Send a welcome to the new client
  79. /// Setup a callback to recieve data
  80. /// </summary>
  81. /// <param name="sockClient">Connection to keep</param>
  82. //public void NewConnection( TcpListener listener )
  83. public void NewConnection(Socket sockClient)
  84. {
  85. SocketClient client = new SocketClient(sockClient);
  86. m_aryClients.Add(client);
  87.  
  88. Console.WriteLine("Client {0}, joined", client.Sock.RemoteEndPoint);
  89.  
  90.  
  91.  
  92. client.SetupRecieveCallback(this);
  93. }
  94. /// <summary>
  95. /// Get the new data and send it out to all other connections.
  96. /// Note: If not data was recieved the connection has probably
  97. /// died.
  98. /// </summary>
  99. /// <param name="ar"></param>
  100. public void OnRecievedData( IAsyncResult ar )
  101. {
  102. SocketClient client = (SocketClient)ar.AsyncState;
  103. byte [] aryRet = client.GetRecievedData( ar );
  104.  
  105.  
  106. if (aryRet.Length !=0)
  107. {
  108.  
  109. String szData = System.Text.ASCIIEncoding.ASCII.GetString(aryRet);
  110. aryRet = null;
  111.  
  112.  
  113. if (szData != null && szData != " " && szData != "" && szData != "nrn" && szData != "rn")
  114. {
  115.  
  116. Console.WriteLine(szData);
  117. try
  118. {
  119. MSMQ msmq = new MSMQ();
  120. msmq.InitializeQueue();
  121. msmq.AddData(szData);
  122. msmq = null;
  123. }
  124. catch (Exception ex1)
  125. {
  126. // Logger.Log("Send failure: " + ex1.Message);
  127. writer.WriteToLog("Send failure: " + ex1.Message);
  128. }
  129. }
  130. client.SetupRecieveCallback(this);
  131. }
  132.  
  133. else if( aryRet.Length < 1 )
  134. {
  135.  
  136. Console.WriteLine( "Client {0}, disconnected", client.Sock.RemoteEndPoint );
  137.  
  138. client.Sock.Close();
  139.  
  140. aryRet = null;
  141.  
  142. m_aryClients.Remove( client );
  143. GC.Collect();
  144. GC.WaitForPendingFinalizers();
  145. return;
  146. }
  147. }
  148.  
  149. internal class SocketClient
  150. {
  151. private Socket m_sock;
  152. private byte[] m_byBuff = new byte[1024]; /// <summary>
  153. /// Constructor
  154. /// </summary>
  155. /// <param name="sock">client socket conneciton this object represents</param>
  156. public SocketClient(Socket sock)
  157. {
  158. m_sock = sock;
  159. }
  160.  
  161. // Readonly access
  162. public Socket Sock
  163. {
  164. get { return m_sock; }
  165. }
  166.  
  167. /// <summary>
  168. /// Setup the callback for recieved data and loss of conneciton
  169. /// </summary>
  170. /// <param name="app"></param>
  171. public void SetupRecieveCallback(SocketServer app)
  172. {
  173. try
  174. {
  175. AsyncCallback recieveData = new AsyncCallback(app.OnRecievedData);
  176. m_sock.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, this);
  177. }
  178. catch (Exception ex)
  179. {
  180. Console.WriteLine("Recieve callback setup failed! {0}", ex.Message);
  181. }
  182. }
  183.  
  184. /// <summary>
  185. /// Data has been recieved so we shall put it in an array and
  186. /// return it.
  187. /// </summary>
  188. /// <param name="ar"></param>
  189. /// <returns>Array of bytes containing the received data</returns>
  190. public byte[] GetRecievedData(IAsyncResult ar)
  191. {
  192. int nBytesRec = 0;
  193. try
  194. {
  195. nBytesRec = m_sock.EndReceive(ar);
  196. }
  197. catch { }
  198. byte[] byReturn = new byte[nBytesRec];
  199. Array.Copy(m_byBuff, byReturn, nBytesRec);
  200.  
  201. return byReturn;
  202. }
  203. }
Add Comment
Please, Sign In to add comment