Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private ArrayList m_aryClients = new ArrayList();
- public void listen()
- {
- try
- {
- // Check the port value
- if (textBoxPort.Text == "")
- {
- MessageBox.Show("Please enter a Port Number");
- return;
- }
- string portStr = textBoxPort.Text;
- try
- {
- // NOTE: DNS lookups are nice and all but quite time consuming.
- strHostName = Dns.GetHostName();
- IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
- aryLocalAddr = ipEntry.AddressList;
- }
- catch (Exception ex)
- {
- Console.WriteLine("Error trying to get local address {0} ", ex.Message);
- }
- // Verify we got an IP address. Tell the user if we did
- if (aryLocalAddr == null || aryLocalAddr.Length < 1)
- {
- Console.WriteLine("Unable to get local address");
- return;
- }
- // Create the listening socket...
- m_mainSocket = new Socket(AddressFamily.InterNetwork,
- SocketType.Stream,
- ProtocolType.Tcp);
- IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
- // Bind to local IP Address...
- m_mainSocket.Bind(ipLocal);
- // Start listening...
- m_mainSocket.Listen(500);
- m_mainSocket.BeginAccept(new AsyncCallback(OnConnectRequest), m_mainSocket);
- UpdateControls(true);
- }
- catch (SocketException se)
- {
- writer.WriteToLog(se.Message);
- }
- }
- /// <summary>
- /// Callback used when a client requests a connection.
- /// Accpet the connection, adding it to our list and setup to
- /// accept more connections.
- /// </summary>
- /// <param name="ar"></param>
- public void OnConnectRequest(IAsyncResult ar)
- {
- Socket listener = (Socket)ar.AsyncState;
- try
- {
- NewConnection(listener.EndAccept(ar));
- listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
- }
- catch (Exception ex)
- {
- }
- }
- /// <summary>
- /// Add the given connection to our list of clients
- /// Note we have a new friend
- /// Send a welcome to the new client
- /// Setup a callback to recieve data
- /// </summary>
- /// <param name="sockClient">Connection to keep</param>
- //public void NewConnection( TcpListener listener )
- public void NewConnection(Socket sockClient)
- {
- SocketClient client = new SocketClient(sockClient);
- m_aryClients.Add(client);
- Console.WriteLine("Client {0}, joined", client.Sock.RemoteEndPoint);
- client.SetupRecieveCallback(this);
- }
- /// <summary>
- /// Get the new data and send it out to all other connections.
- /// Note: If not data was recieved the connection has probably
- /// died.
- /// </summary>
- /// <param name="ar"></param>
- public void OnRecievedData( IAsyncResult ar )
- {
- SocketClient client = (SocketClient)ar.AsyncState;
- byte [] aryRet = client.GetRecievedData( ar );
- if (aryRet.Length !=0)
- {
- String szData = System.Text.ASCIIEncoding.ASCII.GetString(aryRet);
- aryRet = null;
- if (szData != null && szData != " " && szData != "" && szData != "nrn" && szData != "rn")
- {
- Console.WriteLine(szData);
- try
- {
- MSMQ msmq = new MSMQ();
- msmq.InitializeQueue();
- msmq.AddData(szData);
- msmq = null;
- }
- catch (Exception ex1)
- {
- // Logger.Log("Send failure: " + ex1.Message);
- writer.WriteToLog("Send failure: " + ex1.Message);
- }
- }
- client.SetupRecieveCallback(this);
- }
- else if( aryRet.Length < 1 )
- {
- Console.WriteLine( "Client {0}, disconnected", client.Sock.RemoteEndPoint );
- client.Sock.Close();
- aryRet = null;
- m_aryClients.Remove( client );
- GC.Collect();
- GC.WaitForPendingFinalizers();
- return;
- }
- }
- internal class SocketClient
- {
- private Socket m_sock;
- private byte[] m_byBuff = new byte[1024]; /// <summary>
- /// Constructor
- /// </summary>
- /// <param name="sock">client socket conneciton this object represents</param>
- public SocketClient(Socket sock)
- {
- m_sock = sock;
- }
- // Readonly access
- public Socket Sock
- {
- get { return m_sock; }
- }
- /// <summary>
- /// Setup the callback for recieved data and loss of conneciton
- /// </summary>
- /// <param name="app"></param>
- public void SetupRecieveCallback(SocketServer app)
- {
- try
- {
- AsyncCallback recieveData = new AsyncCallback(app.OnRecievedData);
- m_sock.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, this);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Recieve callback setup failed! {0}", ex.Message);
- }
- }
- /// <summary>
- /// Data has been recieved so we shall put it in an array and
- /// return it.
- /// </summary>
- /// <param name="ar"></param>
- /// <returns>Array of bytes containing the received data</returns>
- public byte[] GetRecievedData(IAsyncResult ar)
- {
- int nBytesRec = 0;
- try
- {
- nBytesRec = m_sock.EndReceive(ar);
- }
- catch { }
- byte[] byReturn = new byte[nBytesRec];
- Array.Copy(m_byBuff, byReturn, nBytesRec);
- return byReturn;
- }
- }
Add Comment
Please, Sign In to add comment