Exemplo n.º 1
0
        /*
         * BELOW METHODS ARE FOR THE SERVER'S USE ONLY
         */

        /// <summary>
        /// A method to be called as the server starts. This will assure that the server is
        /// constently listenting fr clients and adds them when a connection is recognized by
        /// a TCP listener.
        /// </summary>
        /// <param name="CallMe"></param>
        public static void ServerAwaitingClientLoop(listenerState.Callback CallMe)
        {
            System.Diagnostics.Debug.WriteLine("Listening for connections");

            //Creates TCP listener
            TcpListener lstnr = new TcpListener(IPAddress.Any, DEFAULT_PORT);

            //Stores the state of the listener in a listener state
            listenerState ls = new listenerState(lstnr, CallMe);


            //Begins an event loop for listening for IP addresses.
            ls.theListener.BeginAcceptSocket(AcceptNewClient, ls);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Callback to be used when someone tries to connect to the server.  Performs the necessary junk and then
        /// calls the ListenerState's callback
        /// </summary>
        /// <param name="ar"></param>
        private static void AcceptNewClient(IAsyncResult ar)
        {
            System.Diagnostics.Debug.WriteLine("Client connected");
            //retrievs the listener state that triggered this method
            listenerState ls = (listenerState)ar.AsyncState;

            //gets socket from the established connection
            Socket socket = ls.theListener.EndAcceptSocket(ar);

            //Grabs the IP address from the remote end of our socket
            IPAddress ip = IPAddress.Parse(((IPEndPoint)socket.RemoteEndPoint).Address.ToString());

            //Creates a socket state
            SocketState ss = new SocketState(socket, ip.GetHashCode());

            //Perfrom's callback method retrieved from the newly connected socket
            ls.CallMe(ss);

            //Restarts the event loop to listen for more clients
            ls.theListener.BeginAcceptSocket(AcceptNewClient, ls);
        }