Esempio n. 1
0
		/// <summary>
		/// Start listen to clients and process connected clients.
		/// </summary>
		public async void Start()
		{
			#region Test code

			DBoperations.Register("13", "13");
			for (int i = 0; i < 10; i++)
			{
				string login = "******" + i.ToString();
				DBoperations.Register(login, login);
			}
			for (int i = 10; i < 20; i++)
			{
				string login = "******" + i.ToString();
				DBoperations.Register(login, login);
				DBoperations.SetFriendship(DBoperations.GetUserId(login), DBoperations.GetUserId("13"), false);
			}
			for (int i = 20; i < 30; i++)
			{
				string login = "******" + i.ToString();
				DBoperations.Register(login, login);
				DBoperations.SetFriendship(DBoperations.GetUserId("13"), DBoperations.GetUserId(login), false);
			}
			for (int i = 30; i < 40; i++)
			{
				string login = "******" + i.ToString();
				DBoperations.Register(login, login);
				DBoperations.SetFriendship(DBoperations.GetUserId("13"), DBoperations.GetUserId(login), true);
			}

			#endregion

			if (isStarted) return;
			if (certificate == null) return;

			mpListener = new MpListener(port, certificate);
			mpListener.Start();
			isStarted = true;

			log.Info("Server is now listening.");

			while (true)
			{
				try
				{
					MpClient client = await mpListener.AcceptMpClientAsync();
					Task t = HandleClient(client);
					activeTasks.Add(t);

					// remove completed tasks
					activeTasks.RemoveAll(x => x.IsCompleted);
				}
				catch (ConnectionInterruptedException e)
				{
					// connection with client broke
					// nothing critical, just continue
					log.Error(e);
					continue;
				}
				catch (SocketException e)
				{
					log.Info("Socket exception. Trying to restart listening.", e);

					mpListener.Stop();
					mpListener = null;
					mpListener = new MpListener(port, certificate);
					mpListener.Start();

					continue;
				}
				catch (ObjectDisposedException)
				{
					// the way we stop server
					break;
				}
			}

			// wait for finishing process clients
			Task.WaitAll(activeTasks.ToArray());

			log.Info("Server is now stopped listening.");
			isStarted = false;
		}
Esempio n. 2
0
		/// <summary>
		/// Stop accepting clients.
		/// </summary>
		public void Stop()
		{
			if (!isStarted) return;

			usersHandler.Dispose();
			mpListener.Stop();
			mpListener = null;
		}