//Clienter der kan tilkoble serveren private void Run() { string productInformation = Console.ReadLine(); try { string[] splitProduct = productInformation.Split('|'); _product = new Product(splitProduct[0], double.Parse(splitProduct[1]), splitProduct[2]); Console.WriteLine("[" + GetDatetime() + "] Server: Produktet er blevet oprettet"); } catch (Exception) { Console.WriteLine("[" + GetDatetime() + "] Server: Du har indtastet produktet i et ugyldigt format! Prøv igen."); Run(); } TcpListener _tcpListener = new TcpListener(IPAddress.Any, _port); _tcpListener.Start(); while (true) { Socket socket = _tcpListener.AcceptSocket(); _clientIP = socket.RemoteEndPoint as IPEndPoint; Console.WriteLine("[" + GetDatetime() + "] Server: {0} er forbundet til serveren.", _clientIP.Address); ClientHandler clientHandler = new ClientHandler(socket, _product, _service, _clientIP); Thread clientThread = new Thread(clientHandler.Run); clientThread.Start(); } }
/// <summary> /// Listens to the specified port and create a new thread to each client, /// </summary> public void Run() { TcpListener listener = new TcpListener(ip, port); listener.Start(); while (true) { Socket clientSocket = listener.AcceptSocket(); ClientHandler handler = new ClientHandler(clientSocket, Controller); ConnectedClients.Add(handler); Thread t = new Thread(handler.Run); t.IsBackground = true; t.Start(); } }
/// <summary> /// Removes ClientHandler from connectedClients and disposes clientHandler /// </summary> /// <param name="clientHandler"></param> public void ClientCleanUp(ClientHandler clientHandler) { Server.ConnectedClients.Remove(clientHandler); clientHandler.Dispose(); }