/// <summary> /// Do handshake for client side. /// </summary> /// <param name="clientSocket"> Socket from client side to server side</param> /// <returns>null if handShake fail otherwise return instance of AProtocol</returns> public async Task <AProtocol> HandShakeClient(NetworkStream clientSocket) { HelloCommand hello = new HelloCommand(ClientConfig.SUPPORTED_PROTOCOLS); await hello.SendAsync(clientSocket); ACommand shouldBeOLLEH = GetCommand(await clientSocket.ReadLineAsync()); if (shouldBeOLLEH is OllehCommand) { OllehCommand olleh = (OllehCommand)shouldBeOLLEH; AProtocol protocol = ClientConfig.PROTOCOL_FACTORY.GetProtocol(olleh.PROTOCOL); if (protocol != null) { AckCommand ack = new AckCommand(); await ack.SendAsync(clientSocket); return(protocol); } ErrorCommand error = new ErrorCommand($"Unsupported protocols '{olleh.PROTOCOL}'. Handshake failed."); await error.SendAsync(clientSocket); } else { printIfErrorElseSendMessage(shouldBeOLLEH, "Handshake error. Expected OllehCommand but receive " + shouldBeOLLEH.GetType().Name, clientSocket); } return(null); }
/// <summary> /// Disconnect networkStream from server and send message. /// </summary> /// <param name="n"></param> /// <param name="message"></param> protected async void disconnect(NetworkStream n, string message) { lock (networkStreamPool) { networkStreamPool.Remove(n); } await Task.Yield(); ErrorCommand error = new ErrorCommand(message); await error.SendAsync(n); n.Close(); }