summaryrefslogtreecommitdiff
blob: 986bbf12ca3a9736503bb528509ac3e855ea0d76 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace Server
{
	public class TcpChatServer
	{
		TcpListener serverSocket;

		public void Start(string ipAddress, int port)
		{
			try
			{
				serverSocket = new TcpListener(IPAddress.Parse(ipAddress), port);
				serverSocket.Start();
				LogSingleton.Instance.Log += "Server started.\n";
				Task.Run(() => Listen(serverSocket));
				LogSingleton.Instance.Log += "Waiting for connections...\n";
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
		}

		private void Listen(TcpListener listener)
		{
			while (true)
			{
				ClientConnection cc = new ClientConnection(listener);
				LogSingleton.Instance.ConnectedClients.Add(cc);
			}
		}

		public void Stop()
		{
			serverSocket.Stop();
			LogSingleton.Instance.Log += "Server stopped\n";
		}

		public void SendMessage(string message)
		{
			foreach (ClientConnection client in LogSingleton.Instance.ConnectedClients) client.StreamWriter.WriteLine(message);
		}
	}
}