From 295e3c10bb6d1c83796554edf8369e5aa87a20a8 Mon Sep 17 00:00:00 2001 From: marcinzelent Date: Mon, 9 Oct 2017 08:56:25 +0200 Subject: Initial commit. --- Server/TcpChatServer.cs | 50 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Server/TcpChatServer.cs (limited to 'Server/TcpChatServer.cs') diff --git a/Server/TcpChatServer.cs b/Server/TcpChatServer.cs new file mode 100644 index 0000000..986bbf1 --- /dev/null +++ b/Server/TcpChatServer.cs @@ -0,0 +1,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); + } + } +} -- cgit v1.2.3