Example #1
0
        static void Main(string[] args)
        {
            var port   = 8005;
            var server = new ServerService(port);

            server.StartServer();
        }
Example #2
0
        private void PingAllServers()
        {
            if (Server.AllServers.Count <= 1)
            {
                return;
            }

            for (int i = 0; i < Server.AllServers.Count; i++)
            {
                if (Server.AllServers[i].ID == Server.My_Identification.ID) //Avoid ping to himself
                {
                    continue;
                }

                try
                {
                    ServerService obj = (ServerService)Activator.GetObject(typeof(ServerService), Server.AllServers[i].UID.AbsoluteUri + "MyRemoteObjectName");
                    obj.Ping();
                    Console.WriteLine("ALIVE: {0}", Server.AllServers[i].UID.AbsoluteUri);
                }
                catch (Exception e)
                {
                    Console.WriteLine("DEAD: {0}", Server.AllServers[i].UID.AbsoluteUri);
                    //Console.WriteLine(e);
                }
            }
        }
Example #3
0
 private void prepareRemoting(int port, string name, int min_delay, int max_delay)
 {
     tupleSpace = new List <TupleClass>();
     channel    = new TcpChannel(port);
     ChannelServices.RegisterChannel(channel, false);
     myRemoteObject = new ServerService(this, min_delay, max_delay);
     RemotingServices.Marshal(myRemoteObject, name, typeof(ServerService));
 }
Example #4
0
        //server functions
        public void Init(string serverLoc)
        {
            leader = false;
            ServerService obj = (ServerService)Activator.GetObject(
                typeof(ServerService),
                serverLoc);

            obj.GetServerInfo(this);
        }
Example #5
0
        /// <summary>
        /// Event Fired when a Client gets connected. Following actions are performed
        /// 1. Update Tree view
        /// 2. Open a chat box to chat with client.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ClientAdded(object sender, EventArgs e)
        {
            tcpClient = ((MyEventArgs)e).clientSock;
            String remoteIP = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
            String remotePort = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port.ToString();

            serverService = new ServerService(ParentForm, tcpClient);
            Variable.SERVERSERVICES.Add(serverService);
            Variable.THREADS.Add(Thread.CurrentThread);
        }
Example #6
0
        private void setServer(String obj)
        {
            _channel = new TcpChannel(_port);
            ChannelServices.RegisterChannel(_channel, false);

            ServerService serverService = new ServerService(this);

            RemotingServices.Marshal(serverService, obj, typeof(ServerService));

            Console.WriteLine("[SERVER:" + _id + "] " + _url + " Delay: " + _min_delay + "ms to " + _max_delay + "ms\n");
        }
Example #7
0
        public List <TupleClass> updateTS()
        {
            while (view.Count == 0)
            {
                Thread.Sleep(100);
            }
            WaitHandle[]      handles      = new WaitHandle[view.Count - 1];
            IAsyncResult[]    asyncResults = new IAsyncResult[view.Count - 1];
            int               i            = 0;
            List <TupleClass> result       = new List <TupleClass>();

            foreach (string url in view)
            {
                if (url == _url)
                {
                    continue;
                }
                ServerService     remoteObject = (ServerService)serverRemoteObjects[url];
                askUpdateDelegate askUpdateDel = new askUpdateDelegate(remoteObject.askUpdate);
                IAsyncResult      ar           = askUpdateDel.BeginInvoke(null, null);
                asyncResults[i] = ar;
                handles[i]      = ar.AsyncWaitHandle;
                i++;
            }
            if (!WaitHandle.WaitAll(handles, 3000))
            {
                return(updateTS()); //TODO
            }
            List <TupleClass> localRes = new List <TupleClass>();

            for (i = 0; i < view.Count - 1; i++)
            {
                try {
                    IAsyncResult      asyncResult  = asyncResults[i];
                    askUpdateDelegate askUpdateDel = (askUpdateDelegate)((AsyncResult)asyncResult).AsyncDelegate;
                    localRes = askUpdateDel.EndInvoke(asyncResult);
                }
                catch (SocketException e) {
                }
                if (i == 0)
                {
                    result = localRes;
                }
                else
                {
                    if (!compareList(result, localRes))
                    {
                        Thread.Sleep(300);//If servers do not agree with the tuple space, we need to let them sync
                        return(updateTS());
                    }
                }
            }
            return(result);
        }
Example #8
0
 public void GetServerInfo(ServerService newServer)
 {
     view.Add(newServer);
     foreach (ServerService serv in view)
     {
         serv.SetServerView(view);
         Console.WriteLine("servReq: " + servSeqNum + ", currentSeq: " + currentSeqNum);
         Status();
         serv.SetInfo(servSeqNum, currentSeqNum, tuples);
         Console.WriteLine("View sent");
     }
 }
Example #9
0
        static void Main(string[] args)
        {
            serverService = new ServerService();

            Model.Server.Thread = new Thread(() => serverService.Start());
            Model.Server.Thread.IsBackground = true;
            Model.Server.Thread.Start();

            while (true)
            {
                serverService.Commands(Console.ReadLine());
            }
        }
Example #10
0
        public static ServerService MakeServerService()
        {
            var serverService = new ServerService();

            serverService.SetUserService(new UserService());
            serverService.SetUserConferenceService(new UserConferenceService());
            serverService.SetAdminConferencesService(new AdminConferenceService());
            serverService.SetAdminUserCheckerService(new AdminUserCheckerService());
            serverService.SetTicketService(new TicketService());
            serverService.SetEmailService(new EmailService());
            serverService.SetPaperService(new ProposalService());
            serverService.SetEnumService(new EnumGetDataService());
            serverService.SetReviewService(new ReviewService());
            serverService.SetSectionService(new SectionService());
            return(serverService);
        }
        public static void Main(string[] args)
        {
            ICaseRepository      caseRepository      = new CaseDbRepository();
            IDonorRepository     donorRepository     = new DonorDbRepository();
            IVolunteerRepository volunteerRepository = new VolunteerDbRepository();
            IDonationRepository  donationRepository  = new DonationDbRepository();

            CaseService      caseService      = new CaseService(caseRepository);
            DonorService     donorService     = new DonorService(donorRepository);
            VolunteerService volunteerService = new VolunteerService(volunteerRepository);
            DonationService  donationService  = new DonationService(donationRepository);

            IService serverService = new ServerService(caseService, donorService, volunteerService, donationService);

            SerialConcurrentServer server = new SerialConcurrentServer("127.0.0.1", 55555, serverService);

            server.Start();
        }
Example #12
0
        public void CompareTerm(int _term, ServerService server)
        {
            Console.WriteLine("COmpara o recebido de servidor " + server.getID() + " :" + _term + "com o meu:" + term);
            if (_term > term)
            {
                state = Estado.FOLLOWER;
                Console.WriteLine("e maior chefe");
                term = _term;
                server.CompareANS();
                electionTimer.Stop();
                electionTimer.Start();


                return;
            }
            else
            {
                Console.WriteLine("Nao e maior chefe");
                return;
            }
        }
        static void Main(string[] args)
        {
            BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider();

            serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
            BinaryClientFormatterSinkProvider clientProv = new BinaryClientFormatterSinkProvider();
            var props = new Hashtable();

            props["port"] = 3291;

            var channel = new TcpChannel(props, clientProv, serverProv);

            ChannelServices.RegisterChannel(channel, false);

            var service = new ServerService();

            RemotingServices.Marshal(service, "Curse");
            Console.WriteLine("Server started ...");
            Console.WriteLine("Press <enter> to exit...");
            Console.ReadLine();
        }
Example #14
0
        private void selfPrepare(int min_delay, int max_delay)
        {
            serverRemoteObjects = new Dictionary <string, IServerService>();
            matchIndexMap       = new Dictionary <string, int>();

            channel = new TcpChannel(_port);
            Console.WriteLine(_port.ToString());
            ChannelServices.RegisterChannel(channel, false);

            myRemoteObject = new ServerService(this, min_delay, max_delay);
            RemotingServices.Marshal(myRemoteObject, _name, typeof(ServerService)); //TODO remote object name
            fd = new FailureDetector();
            Console.WriteLine("Hello! I'm a Server at port " + _port);

            foreach (string url in ConfigurationManager.AppSettings.AllKeys)
            {
                string[] urlSplit = url.Split(new Char[] { '/', ':' }, StringSplitOptions.RemoveEmptyEntries);
                int      portOut;
                Int32.TryParse(urlSplit[2], out portOut);
                //not to connect to himself
                if (portOut != _port)
                {
                    serverRemoteObjects.Add(url, (ServerService)Activator.GetObject(typeof(ServerService), url));
                    matchIndexMap.Add(url, 0);
                }
            }
            _numServers = serverRemoteObjects.Count;

            List <string> view = fd.getView();

            while (view == null || view.Count == 0)
            {
                Thread.Sleep(100);
                view = fd.getView();
            }
            _state = new FollowerState(this, 0);;
            Console.WriteLine("Finished constructing server " + _port + " with thread " + Thread.CurrentThread.ManagedThreadId);
        }
Example #15
0
        public void requestVote()
        {
            Console.WriteLine("request_vote --t " + Thread.CurrentThread.ManagedThreadId);
            if (timerThreadBlock)
            {
                return;
            }
            _term++;
            Console.WriteLine("Started election in term " + _term);
            int votes = 1;

            if (_server.fd.changed())
            {
                _view       = _server.fd.getView();
                _numServers = _view.Count();
                foreach (string url in _view)
                {
                    Console.WriteLine(url);
                }
            }
            Console.WriteLine("after view change");
            WaitHandle[]   handles      = new WaitHandle[_numServers - 1];
            IAsyncResult[] asyncResults = new IAsyncResult[_numServers - 1];
            try {
                int i = 0;
                foreach (string url in _view)
                {
                    if (url == _url)
                    {
                        continue;
                    }
                    ServerService remoteObject = (ServerService)_serverRemoteObjects[url];
                    voteDelegate  voteDel      = new voteDelegate(remoteObject.vote);
                    IAsyncResult  ar           = voteDel.BeginInvoke(_term, _url, null, null);
                    asyncResults[i] = ar;
                    handles[i]      = ar.AsyncWaitHandle;
                    i++;
                }
                if (!WaitHandle.WaitAll(handles, 4000))  //TODO
                {
                    Console.WriteLine("candidate timeout waiting for votes");
                    requestVote();
                }
                else
                {
                    for (i = 0; i < _numServers - 1; i++)
                    {
                        IAsyncResult asyncResult = asyncResults[i];
                        voteDelegate voteDel     = (voteDelegate)((AsyncResult)asyncResult).AsyncDelegate;
                        bool         response    = voteDel.EndInvoke(asyncResult);
                        if (response)
                        {
                            votes++;
                        }
                    }
                    if (votes > (_numServers / 2))
                    {
                        electionTimeout.Stop();
                        timerThreadBlock = true;
                        _server.updateState("leader", _term, _url);
                        _server = null;
                        electionTimeout.Dispose();
                        Console.WriteLine("elected in term" + _term);
                        return;
                    }
                    else
                    {
                        Console.WriteLine("Finished elections without sucess");
                    }
                }
                wait = rnd.Next(1000, 1200);
                electionTimeout.Interval = wait;
                electionTimeout.Enabled  = true;
            }
            catch (SocketException) {
                //TODO
                throw new NotImplementedException();
            }
        }
Example #16
0
        public void pingLoop()
        {
            while (true)
            {
                List <string>  oldView      = view;
                WaitHandle[]   handles      = new WaitHandle[numServers];
                IAsyncResult[] asyncResults = new IAsyncResult[numServers];
                try {
                    int   i         = 0;
                    int[] responses = new int[numServers];
                    foreach (KeyValuePair <string, IServerService> remoteObjectpair in serverRemoteObjects)
                    {
                        ServerService remoteObject = (ServerService)remoteObjectpair.Value;
                        pingDelegate  pingDel      = new pingDelegate(remoteObject.Ping);
                        IAsyncResult  ar           = pingDel.BeginInvoke(null, null);

                        asyncResults[i] = ar;
                        handles[i]      = ar.AsyncWaitHandle;
                        i++;
                    }
                    if (!WaitHandle.WaitAll(handles, 300))
                    {
                        for (int k = 0; k < numServers; k++)
                        {
                            if (handles[k].WaitOne(0) == false)
                            {
                                responses[k] = -1;
                            }
                        }
                    }
                    for (i = 0; i < numServers; i++)
                    {
                        try {
                            if (responses[i] != -1)   //responses with -1 already timed out, we don't want to endinvoke them
                            {
                                IAsyncResult asyncResult = asyncResults[i];
                                pingDelegate pingDel     = (pingDelegate)((AsyncResult)asyncResult).AsyncDelegate;
                                responses[i] = pingDel.EndInvoke(asyncResult);
                            }
                        }
                        catch (SocketException) {
                            responses[i] = -1;
                        }
                        catch (NullReferenceException) {
                            responses[i] = -1;
                        }
                    }
                    lock (view) {
                        view = new List <string>();
                        for (int j = 0; j < numServers; j++)
                        {
                            if (responses[j] != -1)
                            {
                                view.Add(allServers[j]);
                            }
                        }
                    }
                }
                catch (Exception e) {
                    Console.WriteLine(e.StackTrace);
                }

                bool isChanged = false;
                if (oldView.Count != view.Count)
                {
                    isChanged = true;
                }

                foreach (string bla in view)
                {
                    if (!oldView.Contains(bla))
                    {
                        isChanged = true;
                    }
                }
                if (isChanged)
                {
                    modified = true;
                    Console.WriteLine("View Changed. View count: " + view.Count);
                }
            }
        }
Example #17
0
        public void requestVote()
        {
            if (timerThreadBlock)
            {
                return;
            }
            if (_server.fd.changed())
            {
                _view       = _server.fd.getView();
                _numServers = _view.Count();
                foreach (string url in _view)
                {
                    if (!votemap.ContainsKey(url))
                    {
                        votemap.Add(url, false);
                    }
                }
                foreach (KeyValuePair <string, bool> entry in votemap)
                {
                    if (!_view.Contains(entry.Key))
                    {
                        votemap.Remove(entry.Key);
                    }
                }
            }

            int howmany = 0;

            foreach (KeyValuePair <string, bool> entry in votemap)
            {
                if (!entry.Value)
                {
                    howmany++;
                }
            }

            WaitHandle[]   handles      = new WaitHandle[howmany];
            IAsyncResult[] asyncResults = new IAsyncResult[howmany];
            string[]       requestId    = new string[howmany];
            try {
                int i = 0;
                foreach (KeyValuePair <string, bool> entry in votemap)
                {
                    if (entry.Value)
                    {
                        continue;
                    }
                    ServerService remoteObject = (ServerService)_serverRemoteObjects[entry.Key];
                    voteDelegate  voteDel      = new voteDelegate(remoteObject.vote);
                    IAsyncResult  ar           = voteDel.BeginInvoke(_term, _url, null, null);
                    asyncResults[i] = ar;
                    handles[i]      = ar.AsyncWaitHandle;
                    requestId[i]    = entry.Key;
                    i++;
                }
                if (!WaitHandle.WaitAll(handles, 100))
                {
                    requestVote();
                }
                else
                {
                    for (i = 0; i < howmany; i++)
                    {
                        IAsyncResult asyncResult = asyncResults[i];
                        voteDelegate voteDel     = (voteDelegate)((AsyncResult)asyncResult).AsyncDelegate;
                        bool         response    = voteDel.EndInvoke(asyncResult);
                        votemap.Remove(requestId[i]);
                        votemap.Add(requestId[i], true);
                        if (response)
                        {
                            votes++;
                        }
                    }
                    if (votes > (_numServers / 2))
                    {
                        stopClock();
                        timerThreadBlock = true;
                        _server.updateState("leader", _term, _url);
                        _server = null;
                        Console.WriteLine("Elected in term " + _term);
                        return;
                    }
                    else
                    {
                        Console.WriteLine("Finished elections without success.");
                        pulseVote.Stop();
                        pulseVote.Dispose();
                        SetVoteTimer();
                    }
                }
            }
            catch (SocketException) {
                requestVote();
            }
        }
Example #18
0
        public void pulseAppendEntry()
        {
            if (timerThreadBlock)
            {
                return;
            }
            int sucess = 1;

            timer.Enabled = true;
            if (_server.fd.changed())
            {
                _view       = _server.fd.getView();
                _numServers = _view.Count();
            }
            Dictionary <int, string> i_url_map = new Dictionary <int, string>();

            WaitHandle[]   handles      = new WaitHandle[_numServers - 1];
            IAsyncResult[] asyncResults = new IAsyncResult[_numServers - 1];
            try {
                int i = 0;
                foreach (string url in _view)
                {
                    if (url == _url)
                    {
                        continue;
                    }
                    EntryPacket entryPacket = new EntryPacket();
                    int         theirIndex  = _server.matchIndexMap[url];
                    int         myindex     = _server.getLogIndex();
                    if (myindex != theirIndex)
                    {
                        for (int k = theirIndex; k < myindex; k++)
                        {
                            entryPacket.Add(_server.entryLog[k]);
                        }
                    }
                    ServerService       remoteObject   = (ServerService)_serverRemoteObjects[url];
                    appendEntryDelegate appendEntryDel = new appendEntryDelegate(remoteObject.appendEntry);
                    IAsyncResult        ar             = appendEntryDel.BeginInvoke(entryPacket, _term, _url, null, null);
                    asyncResults[i] = ar;
                    handles[i]      = ar.AsyncWaitHandle;
                    i_url_map.Add(i, url);
                    i++;
                }
                if (!WaitHandle.WaitAll(handles, 5000))  //TODO esta desoncronizado
                {
                    pulseHeartbeat();
                }
                else
                {
                    foreach (KeyValuePair <int, string> entry in i_url_map)
                    {
                        IAsyncResult        asyncResult    = asyncResults[entry.Key];
                        appendEntryDelegate appendEntryDel = (appendEntryDelegate)((AsyncResult)asyncResult).AsyncDelegate;
                        EntryResponse       response       = appendEntryDel.EndInvoke(asyncResult);
                        if (!response.Sucess)          //foi false
                        {
                            if (_term < response.Term) //term da resposta e maior do que o meu
                            {
                                Console.WriteLine("Leader -> Follower : pulseappendEntry");
                                timerThreadBlock = true;
                                _server.updateState("follower", _term, response.Leader);
                                _server = null;
                                timer.Dispose();
                            }
                            //nao estou a tratar quando da false por causa do log aqui especificamente
                            //trato tudo da mesma maneira
                        }
                        //se tiver ter dado true e porque os 2 estao up to date, logo atualizo o dele para o bem
                        //se tiver dado false, meto no mapa nao contando para os sucessos,
                        //depois no heartbeat a seguir deve sincronizar teoricamente :)
                        _server.matchIndexMap[entry.Value] = response.MatchIndex;
                        if (response.Sucess)
                        {
                            sucess++;
                        }
                    }
                    if (!(sucess > (_numServers / 2)))
                    {
                        pulseAppendEntry();
                    }
                }
            }
            catch (ElectionException) {
                //nao sei se e preciso tratar visto que nao pode existir 1 lider e 1 candidato ao mesmo tempo
            }
            catch (SocketException) {
                //TODO
                throw new NotImplementedException();
            }
        }
Example #19
0
        static void Main(string[] args)
        {
            string[] conf;
            string   myRemoteObject = null;
            string   serverLoc = null;
            int      maxDelay = 0, minDelay = 0;

            if (args.Length == 0)      //le do ficheiro
            {
                conf = ReadConfFile(); //pos 0 is port -- pos 1 is type
            }
            else //le dos argumentos
            {
                conf           = ReadArgs(args);
                minDelay       = System.Convert.ToInt32(conf[3]);
                maxDelay       = System.Convert.ToInt32(conf[4]);
                myRemoteObject = conf[5];
            }


            if (!conf[2].Equals("null"))
            {
                serverLoc = conf[2];
                //serverLoc = System.Configuration.ConfigurationManager.AppSettings["server"];
            }

            Console.WriteLine("Port:{0}\nType:{1}\nObj:{2}", conf[0], conf[1], myRemoteObject);

            BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();

            provider.TypeFilterLevel = TypeFilterLevel.Full;
            IDictionary props = new Hashtable();

            props["port"]              = System.Convert.ToInt32(conf[0]);
            props["timeout"]           = 100;
            props["connectionTimeout"] = 100;

            TcpChannel channel = new TcpChannel(props, null, provider);

            ChannelServices.RegisterChannel(channel, true);

            ServerService mo = new ServerService(System.Convert.ToInt32(conf[1]), minDelay, maxDelay, serverLoc, args[6]);

            Console.WriteLine(serverLoc);
            if (serverLoc != null)
            {
                mo.Init(serverLoc);
            }
            if (System.Convert.ToInt32(conf[1]) == 1)
            {
                mo.SetTimer();
            }

            RemotingServices.Marshal(mo, myRemoteObject,
                                     typeof(ServerService));

            System.Console.WriteLine("<enter> para sair...");


            System.Console.ReadLine();
            mo.Logout();
        }
Example #20
0
        private void NetworkStatusStateMachine()
        {
            bool flag = false;

            switch (STATE_MACHINE_NETWORK)
            {
            case STATE_MACHINE_NETWORK_START:
                //Console.WriteLine("IN STATE_MACHINE_NETWORK_START: BEGIN");
                serversAlive.Clear();

                for (int i = 0; i < Server.AllServers.Count; i++)
                {
                    if (Server.AllServers[i].ID == Server.My_Identification.ID)     //Avoid ping himself
                    {
                        continue;
                    }

                    try
                    {
                        ServerService obj = (ServerService)Activator.GetObject(typeof(ServerService), Server.AllServers[i].UID.AbsoluteUri + "MyRemoteObjectName");
                        //Console.WriteLine("CHECK: {0}", Server.AllServers[i].UID.AbsoluteUri);

                        if (obj.isRoot() == true)
                        {
                            Root_id = i;                                                                         //ID of the current root node

                            Console.WriteLine("My old Image is: {0}\n", ServerService.getImageRepresentation()); //OLD

                            ServerService.setImage(obj.getImage());                                              //get the image of the root


                            STATE_MACHINE_NETWORK = STATE_MACHINE_NETWORK_KEEP_ALIVE;
                            flag = true;
                            Console.WriteLine("ROOT is {0}", Server.AllServers[i].UID.AbsoluteUri);
                            Console.WriteLine("My new Image is: {0}\n", ServerService.getImageRepresentation());     //NEW
                            break;
                        }
                        else
                        {
                            serversAlive.Add(i);     //Server ID
                            Console.WriteLine("ALIVE: {0}", Server.AllServers[i].UID.AbsoluteUri);
                        }
                    }
                    catch (Exception e)
                    {
                        //Console.WriteLine("IN STATE_MACHINE_NETWORK_START: EXCEPTION");
                        Console.WriteLine("DEAD: {0}", Server.AllServers[i].UID.AbsoluteUri);
                        //Console.WriteLine(e);
                    }
                }
                //Console.WriteLine("IN STATE_MACHINE_NETWORK_START: TEST_FLAG");
                if (flag == false)
                {
                    //Console.WriteLine("FLAG==FALSE: {0}", serversAlive.Count);
                    if (serversAlive.Count == 0)     //check if anyone is ROOT
                    {
                        //ROOT
                        ServerService.setRoot(true);
                        STATE_MACHINE_NETWORK = STATE_MACHINE_NETWORK_IM_ROOT;
                    }
                    else
                    {
                        //Console.WriteLine("MY_IDENTIFICATION: {0}, {1}", Server.My_Identification.ID, (int)serversAlive[0]);
                        if ((Server.My_Identification.ID - 1) < (int)serversAlive[0])
                        {
                            //ROOT
                            ServerService.setRoot(true);
                            STATE_MACHINE_NETWORK = STATE_MACHINE_NETWORK_IM_ROOT;
                        }
                    }
                }
                break;

            case STATE_MACHINE_NETWORK_KEEP_ALIVE:
                //Console.WriteLine("IN STATE_MACHINE_NETWORK_KEEP_ALIVE");
                //ping root
                try
                {
                    ServerService obj = (ServerService)Activator.GetObject(typeof(ServerService), Server.AllServers[Root_id].UID.AbsoluteUri + "MyRemoteObjectName");
                    obj.Ping();
                    //Console.WriteLine("ALIVE: {0}", Server.AllServers[i].UID.AbsoluteUri);
                    Thread.Sleep(rand.Next(1000));     //keepalive
                }
                catch (Exception e)
                {
                    STATE_MACHINE_NETWORK = STATE_MACHINE_NETWORK_START;

                    //Console.WriteLine("IN STATE_MACHINE_NETWORK_KEEP_ALIVE: EXCEPTION");

                    //Console.WriteLine("GOING TO STATE_MACHINE_NETWORK_START");
                    //Console.WriteLine("DEAD: {0}", Server.AllServers[i].UID.AbsoluteUri);
                    //Console.WriteLine(e);
                }
                break;

            case STATE_MACHINE_NETWORK_IM_ROOT:
                Console.WriteLine("ROOT SERVER");

                ServerService.add("OLA");     //I'm root. I add OLA

                STATE_MACHINE_NETWORK = STATE_MACHINE_NETWORK_END;
                break;

            case STATE_MACHINE_NETWORK_END:
                break;
            }
        }
Example #21
0
 public void RemoveId(ServerService server)
 {
     view.Remove(server);
 }
Example #22
0
        static void Main(string[] args)
        {
            var server = new ServerService(8005);

            server.Start();
        }
Example #23
0
        public void pingLoop()
        {
            while (true)
            {
                if (!_server.frozen)
                {
                    List <string>  oldView      = view;
                    WaitHandle[]   handles      = new WaitHandle[numServers];
                    IAsyncResult[] asyncResults = new IAsyncResult[numServers];
                    try {
                        int   i         = 0;
                        int[] responses = new int[numServers];
                        foreach (KeyValuePair <string, IServerService> remoteObjectpair in serverRemoteObjects)
                        {
                            ServerService remoteObject = (ServerService)remoteObjectpair.Value;
                            pingDelegate  pingDel      = new pingDelegate(remoteObject.Ping);
                            IAsyncResult  ar           = pingDel.BeginInvoke(null, null);

                            asyncResults[i] = ar;
                            handles[i]      = ar.AsyncWaitHandle;
                            i++;
                        }
                        if (!WaitHandle.WaitAll(handles, 300))
                        {
                            for (int k = 0; k < numServers; k++)
                            {
                                if (handles[k].WaitOne(timeouts[k]) == false)
                                {
                                    responses[k] = -2;
                                    if (!suspects.Contains(allServers[k]))   //timeout e ainda não era suspeito
                                    {
                                        Console.WriteLine("Added " + allServers[k] + " to suspects list");
                                        suspects.Add(allServers[k]);
                                    }
                                }
                            }
                        }
                        for (i = 0; i < numServers; i++)
                        {
                            try {
                                if (responses[i] != -2)   //responses with -2 already timed out, we don't want to endinvoke them
                                {
                                    IAsyncResult asyncResult = asyncResults[i];
                                    pingDelegate pingDel     = (pingDelegate)((AsyncResult)asyncResult).AsyncDelegate;
                                    responses[i] = pingDel.EndInvoke(asyncResult);
                                }
                            }
                            catch (SocketException e) {
                                responses[i] = -1;  // -1 means they are dead
                            }
                            catch (NullReferenceException e) {
                                responses[i] = -1;
                            }
                        }
                        lock (view) {
                            view = new List <string>();
                            for (int j = 0; j < numServers; j++)
                            {
                                if (responses[j] != -1)
                                {
                                    view.Add(allServers[j]);
                                }
                                if (responses[j] != -1 && responses[j] != -2 && suspects.Contains(allServers[j]))
                                {
                                    suspects.Remove(allServers[j]);
                                    timeouts[j] += 100;
                                    Console.WriteLine("Increased timeout (" + allServers[j] + " - " + timeouts[j].ToString() + ")");
                                }
                            }
                        }
                    }
                    catch (Exception e) {
                        Console.WriteLine(e.StackTrace);
                    }
                    bool isChanged = false;
                    if (oldView.Count != view.Count)
                    {
                        isChanged = true;
                    }

                    foreach (string str in view)
                    {
                        if (!oldView.Contains(str))
                        {
                            isChanged = true;
                        }
                    }
                    if (isChanged)
                    {
                        Console.WriteLine("View Changed");
                    }
                }
                else
                {
                    Thread.Sleep(100);
                }
            }
        }