using SharedClientServer; using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Text; namespace Server.Models { class ServerCommunication : ObservableObject { private TcpListener listener; private List serverClients; public bool Started = false; /// /// use a padlock object to make sure the singleton is thread-safe /// private static readonly object padlock = new object(); private static ServerCommunication instance = null; public int port = 5555; private ServerCommunication() { listener = new TcpListener(IPAddress.Any, port); serverClients = new List(); } /// /// returns the singleton serverCommunication instance /// public static ServerCommunication INSTANCE { get { lock (padlock) { if (instance == null) { instance = new ServerCommunication(); } } return instance; } } /// /// start the server and start listening on port 5555 and begin acceptinc tcp clients /// public void Start() { listener.Start(); Debug.WriteLine($"================================================\nStarted Accepting clients at {DateTime.Now}\n================================================"); Started = true; // when we have accepted a tcp client, call the onclientconnected callback method listener.BeginAcceptTcpClient(new AsyncCallback(OnClientConnected), null); } /// /// callback method that gets called when a client is accepted /// /// the result of the asynchronous connect call private void OnClientConnected(IAsyncResult ar) { // stop the acceptation TcpClient tcpClient = listener.EndAcceptTcpClient(ar); Console.WriteLine($"Got connection from {tcpClient.Client.RemoteEndPoint}"); // create a new serverclient object and add it to the list serverClients.Add(new ServerClient(tcpClient)); //start listening for new tcp clients listener.BeginAcceptTcpClient(new AsyncCallback(OnClientConnected), null); } /// /// send a message to all tcp clients in the list /// /// the message to send public void sendToAll(byte[] message) { foreach (ServerClient sc in serverClients) { sc.sendMessage(message); } } public void sendToAllExcept(string username, byte[] message) { foreach (ServerClient sc in serverClients) { if (sc.Username != username) sc.sendMessage(message); } } } }