public void ReceivingData(object state) { var client = (TcpClient)state; int i; // Buffer for reading data var bytes = new byte[256]; string data = null; // Loop to receive all the data sent by the client. while (client.Connected) { try { Array.Clear(bytes, 0, bytes.Length); var stream = client.GetStream(); var length = stream.Read(bytes, 0, bytes.Length); CommandPackage package = new CommandPackage( (ServerCommands)bytes[0], bytes.Skip(1).Take(length).ToArray(), client.Client.RemoteEndPoint); // Translate data bytes to a ASCII string. ReceivePackage(package); stream.Flush(); } catch (Exception e) { PrintUtils.PrintImportant(string.Format("Client Disconnected ({0})", client.Client.RemoteEndPoint)); } } }
private static void Login(Socket client, String data, Connection connection) { var message = data.Split("%"); string username = message[0]; string password = message[1]; CommandPackage response; ILog log; try { connection.User = Server.GetInstance().Login(username, password); response = new CommandPackage(HeaderConstants.Response, CommandConstants.Login, MessageConstants.SuccessfulLogin); log = new Info(); log.User = username; log.Message = "Login exitoso"; } catch (Exception ex) { response = new CommandPackage(HeaderConstants.Response, CommandConstants.Login, MessageConstants.FailedLogin); log = new Warning(); log.User = username; log.Message = "Login no valido"; } Server.GetInstance().LogAction(log); CommandProtocol.SendCommand(client, response); }
private static void Menu(ref bool keepRunning, Socket socket, GreeterClient client) { Console.WriteLine(separador); Console.WriteLine("Bienvenido al menu principal de administrador, ingresa la opcion que deseas realizar \n 1-ABM usuario \n 2-Ver logs \n 3-Lista de usuarios \n 4-Exit"); var input = Console.ReadLine(); switch (input) { case "1": ABMMenuAsync(client); break; case "2": LogMenu(socket); break; case "3": ListUsers(client); break; case "4": CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.Exit); CommandProtocol.SendCommand(socket, package); socket.Shutdown(SocketShutdown.Both); socket.Close(); keepRunning = false; break; default: Console.WriteLine("Opcion no valida"); break; } }
private static void Register(Socket client, String data, Connection connection) { //lock (registerLocker) //{ var message = data.Split("%"); string username = message[0]; string password = message[1]; CommandPackage response; ILog log; try { connection.User = Server.GetInstance().RegisterUser(username, password); response = new CommandPackage(HeaderConstants.Response, CommandConstants.Register, MessageConstants.SuccessfulRegister); log = new Info(); log.User = username; log.Message = "Usuario registrado correctamente"; } catch (Exception ex) { response = new CommandPackage(HeaderConstants.Response, CommandConstants.Register, MessageConstants.FailedRegister); log = new Warning(); log.User = username; log.Message = "Registro no valido, nombre de usuario en uso"; } Server.GetInstance().LogAction(log); CommandProtocol.SendCommand(client, response); // } }
private static void PictureList(Socket client, Connection connection, String data) { User user; if (data == "") { user = connection.User; } else { user = Server.GetInstance().GetUser(data); } CommandPackage response; ILog log; if (user != null) { response = new CommandPackage(HeaderConstants.Response, CommandConstants.PictureList); CommandProtocol.SendCommand(client, response); CommandProtocol.SendList(client, user.PictureList(), CommandConstants.PictureList); log = new Info(); log.User = connection.User.Name; log.Message = "Usuario solicita fotos de " + user.Name; } else { response = new CommandPackage(HeaderConstants.Response, CommandConstants.Error); CommandProtocol.SendCommand(client, response); log = new Warning(); log.User = connection.User.Name; log.Message = "Solicita fotos de usuario no valido"; } Server.GetInstance().LogAction(log); }
private static void CommentList(Socket client, Connection connection, String data) { Photo photo = connection.User.GetPhoto(data); CommandPackage response; ILog log; if (photo != null) { response = new CommandPackage(HeaderConstants.Response, CommandConstants.CommentList); CommandProtocol.SendCommand(client, response); CommandProtocol.SendList(client, photo.CommentList(), CommandConstants.CommentList); log = new Info(); log.User = connection.User.Name; log.Message = "Usuario solicita comentarios de la foto " + photo.Name; } else { response = new CommandPackage(HeaderConstants.Response, CommandConstants.Error); CommandProtocol.SendCommand(client, response); log = new Warning(); log.User = connection.User.Name; log.Message = "Solicita comentarios de foto no valida"; } Server.GetInstance().LogAction(log); }
private static void LoginMainMenu(ref bool keepRunning, Socket socket) { Console.WriteLine(separador); Console.WriteLine("Bienvenido al menu principal, ingresa a tu cuenta o registrate \n 1-Login \n 2-Register \n 3-Exit"); var input = Console.ReadLine(); switch (input) { case "1": LoginMenu(socket); break; case "2": RegisterMenu(socket); break; case "3": CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.Exit); CommandProtocol.SendCommand(socket, package); socket.Shutdown(SocketShutdown.Both); socket.Close(); keepRunning = false; break; default: Console.WriteLine("Opcion no valida"); break; } }
public void TestMethod1() { CommandPackage package = new CommandPackage("192.168.0.200", "6765"); PackageBase a = JsonConvert.DeserializeObject <PackageBase>(Encoding.UTF8.GetString(package.Body)); switch (a.Type) { case PackageType.Commond: package = a as CommandPackage; break; case PackageType.Text: break; case PackageType.Image: break; case PackageType.Video: break; case PackageType.Sound: break; default: break; } }
private static void LogMenu(Socket socket) { Console.WriteLine(separador); Console.WriteLine("Ingresa que tipo de logs deseas ver \n 1-Todos los logs \n 2-Info \n 3-Warning \n 4-Error"); var input = Console.ReadLine(); List <string> result = new List <string>(); CommandPackage request; string ammount; switch (input) { case "1": Console.WriteLine("Ingrese la cantidad de logs que desea ver"); ammount = Console.ReadLine(); request = new CommandPackage(HeaderConstants.Request, CommandConstants.Logs, ammount); CommandProtocol.SendCommand(socket, request); result = CommandProtocol.RecieveList(socket); break; case "2": Console.WriteLine("Ingrese la cantidad de logs que desea ver"); ammount = Console.ReadLine(); request = new CommandPackage(HeaderConstants.Request, CommandConstants.LogInfo, ammount); CommandProtocol.SendCommand(socket, request); result = CommandProtocol.RecieveList(socket); break; case "3": Console.WriteLine("Ingrese la cantidad de logs que desea ver"); ammount = Console.ReadLine(); request = new CommandPackage(HeaderConstants.Request, CommandConstants.LogWarning, ammount); CommandProtocol.SendCommand(socket, request); result = CommandProtocol.RecieveList(socket); break; case "4": Console.WriteLine("Ingrese la cantidad de logs que desea ver"); ammount = Console.ReadLine(); request = new CommandPackage(HeaderConstants.Request, CommandConstants.LogError, ammount); CommandProtocol.SendCommand(socket, request); result = CommandProtocol.RecieveList(socket); break; default: Console.WriteLine("Opcion no valida"); break; } if (result.Count > 0) { foreach (string log in result) { Console.WriteLine(log); } } }
private static void ListUsers(Socket socket) { CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.UserList); CommandProtocol.SendCommand(socket, package); List <string> list = CommandProtocol.RecieveList(socket); foreach (string user in list) { Console.WriteLine(user); } }
public void SendPackage(CommandPackage package) { var bytes = new List <byte>(package.data); bytes.Insert(0, (byte)package.command); var stream = tcpClient.GetStream(); stream.Write(bytes.ToArray(), 0, bytes.Count); stream.Flush(); stream = null; }
private void SendCommand(TcpClient client, ResponsePackage refPackage, Commands commands) { BinaryFormatter formater = new BinaryFormatter(); NetworkStream ns = client.GetStream(); CommandPackage cp = new CommandPackage(); cp.Command = commands; lock (ns) { formater.Serialize(ns, cp); } ThreadOnLoggingEventsFired(string.Format("send commands '{0}' to {1}", commands, refPackage.Tag)); }
private static void RequestLoggedUser(Socket client, Connection connection) { CommandPackage response; if (connection.User == null) { response = new CommandPackage(HeaderConstants.Response, CommandConstants.RequestLoggedUser, MessageConstants.NoUserFound); } else { response = new CommandPackage(HeaderConstants.Response, CommandConstants.RequestLoggedUser, connection.User.Name); } CommandProtocol.SendCommand(client, response); }
static Commands GetCommand(TcpClient client) { BinaryFormatter formatter = new BinaryFormatter(); NetworkStream ns = client.GetStream(); CommandPackage cp = formatter.Deserialize(ns) as CommandPackage; if (cp != null) { Console.WriteLine("get command: " + cp.Command); return(cp.Command); } Console.WriteLine("get null command, treat as surpress"); return(Commands.Surpress); }
private void AdminWarning(Socket socket, CommandPackage package) { List <ILog> warnings = new List <ILog>(); foreach (ILog log in logs) { if (log is Warning) { warnings.Add(log); } } List <string> list = ReturnLastN(warnings, int.Parse(package.Data)); CommandProtocol.SendList(socket, list, package.Command); }
private void AdminError(Socket socket, CommandPackage package) { List <ILog> errors = new List <ILog>(); foreach (ILog log in logs) { if (log is Error) { errors.Add(log); } } List <string> list = ReturnLastN(errors, int.Parse(package.Data)); CommandProtocol.SendList(socket, list, package.Command); }
public void ReceivePackage(CommandPackage package) { switch (package.command) { case ServerCommands.BROADCAST: ReceivedPackage?.Invoke(this, package); // PrintUtils.PrintNormal(Encoding.ASCII.GetString(package.data, 0, package.data.Length)); break; case ServerCommands.MESSAGE: ReceivedPackage?.Invoke(this, package); // PrintUtils.PrintNormal(Encoding.ASCII.GetString(package.data, 0, package.data.Length)); break; } }
private static void MainMenu(ref bool keepRunning, Socket socket) { CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.RequestLoggedUser); CommandProtocol.SendCommand(socket, package); CommandPackage response = CommandProtocol.RecieveCommand(socket); if (response.Data == MessageConstants.NoUserFound) { LoginMainMenu(ref keepRunning, socket); } else { LoggedMainMenu(ref keepRunning, socket, response.Data); } }
private static void RegisterMenu(Socket socket) { Console.WriteLine(separador); Console.WriteLine("Ingrese nombre de usuario"); bool validInput = false; string username = ""; while (!validInput) { username = Console.ReadLine(); if (username.Contains("%") || username.Trim().Length == 0) { Console.WriteLine("Su nombre de usuario no puede ser vacio ni contener %"); } else { validInput = true; } } validInput = false; Console.WriteLine("Ingrese contraseña"); string password = ""; while (!validInput) { password = Console.ReadLine(); if (password.Contains("%") || password.Trim().Length == 0) { Console.WriteLine("Su contraseña no puede ser vacia ni contener %"); } else { validInput = true; } } CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.Register, username + "%" + password); CommandProtocol.SendCommand(socket, package); CommandPackage response = CommandProtocol.RecieveCommand(socket); if (response.Data == MessageConstants.FailedRegister) { Console.WriteLine("Ese nombre de usuario ya esta en uso"); } }
private static void LoginMenu(Socket socket) { Console.WriteLine(separador); Console.WriteLine("Ingrese nombre de usuario"); var username = Console.ReadLine(); Console.WriteLine("Ingrese contraseña"); var password = Console.ReadLine(); CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.Login, username + "%" + password); CommandProtocol.SendCommand(socket, package); CommandPackage response = CommandProtocol.RecieveCommand(socket); if (response.Data == MessageConstants.FailedLogin) { Console.WriteLine("Usuario y/o contraseña incorrectos"); } }
private static void ListPhotos(Socket socket) { Console.WriteLine("Inserte el usuario del cual desea ver las fotos, si desea ver las suyas puede dejar en blanco"); var user = Console.ReadLine(); CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.PictureList, user); CommandProtocol.SendCommand(socket, package); CommandPackage response = CommandProtocol.RecieveCommand(socket); if (response.Command == CommandConstants.PictureList) { List <string> pictures = CommandProtocol.RecieveList(socket); if (pictures.Count != 0) { if (user == "") { Console.WriteLine("Sus fotos son:"); } else { Console.WriteLine("Las fotos de " + user + " son:"); } foreach (string picture in pictures) { Console.WriteLine(picture); } } else { if (user == "") { user = "******"; } Console.WriteLine(user + " no tiene fotos actualmente"); } } else { Console.WriteLine("Usuario invalido"); } }
private static void AddComment(Socket socket) { Console.WriteLine("Indique el usuario al cual pertenece la foto que desea comentar"); var user = Console.ReadLine(); Console.WriteLine("Indique la foto que desea comentar"); var photo = Console.ReadLine(); Console.WriteLine("Ingrese el comentario"); var comment = Console.ReadLine(); var data = user + "%" + photo + "%" + comment; CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.NewComment, data); CommandProtocol.SendCommand(socket, package); CommandPackage response = CommandProtocol.RecieveCommand(socket); Console.WriteLine(response.Data); }
public void SendPackage(CommandPackage package) { var bytes = new List <byte>(package.data); bytes.Insert(0, (byte)package.command); clients.RemoveAll(client => !client.Connected); NetworkStream stream; clients.ForEach(client => { if (client.Client.RemoteEndPoint != package.client) { stream = client.GetStream(); stream.Write(bytes.ToArray(), 0, bytes.Count); stream.Flush(); stream = null; } }); }
private static void UploadPicture(Socket socket) { Console.WriteLine("Por favor inserte el path de la imagen que desea subir"); string path = Console.ReadLine(); while (path.Equals(string.Empty) || !FileHandler.FileExists(path)) { Console.WriteLine("path invalido"); path = Console.ReadLine(); } Console.WriteLine("Ingrese el nombre que desea darle a la foto"); string name = Console.ReadLine(); CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.SendPicture, name); CommandProtocol.SendCommand(socket, package); FileProtocol fileProtocol = new FileProtocol(socket); fileProtocol.SendFile(path); Console.WriteLine("Su foto fue subida con exito"); }
private static void LoggedMainMenu(ref bool keepRunning, Socket socket, String username) { Console.WriteLine(separador); Console.WriteLine("Bienvenido {0}!", username); Console.WriteLine("\n 1-Subir Foto \n 2-Listado usuarios sistema \n 3-Listado fotos usuario \n 4-Ver comentarios de mis fotos \n 5-Agregar comentario \n 6-Salir"); var input = Console.ReadLine(); switch (input) { case "1": UploadPicture(socket); break; case "2": ListUsers(socket); break; case "3": ListPhotos(socket); break; case "4": ListComments(socket); break; case "5": AddComment(socket); break; case "6": CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.Logout); CommandProtocol.SendCommand(socket, package); break; default: Console.WriteLine("Opcion no valida"); break; } }
private static void AddComment(Socket client, Connection connection, String data) { var dataStruct = data.Split('%'); User user = Server.GetInstance().GetUser(dataStruct[0]); CommandPackage response; ILog log; if (user != null) { Photo photo = user.GetPhoto(dataStruct[1]); if (photo != null) { Comment comment = new Comment(); comment.User = user; comment.Text = dataStruct[2]; photo.Comments.Add(comment); response = new CommandPackage(HeaderConstants.Response, CommandConstants.NewComment, "Comentario ingresado con exito"); log = new Info(); log.User = connection.User.Name; log.Message = "Usuario comenta la foto " + photo.Name + " del usuario " + user.Name; } else { response = new CommandPackage(HeaderConstants.Response, CommandConstants.Error, "El usuario no contiene una foto con ese nombre"); log = new Warning(); log.User = connection.User.Name; log.Message = "Intenta comentar una foto inexistente del usuario " + user.Name; } } else { response = new CommandPackage(HeaderConstants.Response, CommandConstants.Error, "El usuario ingresado no es valido"); log = new Warning(); log.User = connection.User.Name; log.Message = "Intenta comentar una foto de usuario no existente"; } CommandProtocol.SendCommand(client, response); Server.GetInstance().LogAction(log); }
private static void HandleAdmin(Socket socket) { bool keepRunning = true; while (keepRunning) { try { CommandPackage package = CommandProtocol.RecieveCommand(socket); switch (package.Command) { case CommandConstants.Logs: LogServer.GetInstance().AdminLog(socket, package); break; case CommandConstants.LogInfo: LogServer.GetInstance().AdminInfo(socket, package); break; case CommandConstants.LogWarning: LogServer.GetInstance().AdminWarning(socket, package); break; case CommandConstants.LogError: LogServer.GetInstance().AdminError(socket, package); break; } } catch (Exception ex) { keepRunning = false; socket.Shutdown(SocketShutdown.Both); socket.Close(); } } }
public void ReceivingData() { // Buffer for reading data var bytes = new byte[256]; string data = null; // Loop to receive all the data sent by the client. while (tcpClient.Connected) { try { Array.Clear(bytes, 0, bytes.Length); var stream = tcpClient.GetStream(); var length = stream.Read(bytes, 0, bytes.Length); CommandPackage package = new CommandPackage( (ServerCommands)bytes[0], bytes.Skip(1).Take(length).ToArray(), tcpClient.Client.RemoteEndPoint); // Translate data bytes to a ASCII string. ReceivePackage(package); stream.Flush(); } catch (Exception e) { // Console.BackgroundColor = ConsoleColor.Red; // Console.ForegroundColor = ConsoleColor.White; // Console.WriteLine(e.ToString()); // Console.ResetColor(); PrintUtils.PrintWarning(string.Format("Server Disconnected ({0})", tcpClient.Client.RemoteEndPoint)); throw new ServerLostEsception(); } } }
private static void ListComments(Socket socket) { Console.WriteLine("Indique de que foto desea ver los comentarios"); var photo = Console.ReadLine(); CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.CommentList, photo); CommandProtocol.SendCommand(socket, package); CommandPackage response = CommandProtocol.RecieveCommand(socket); if (response.Command == CommandConstants.CommentList) { Console.WriteLine("Los comentarios son:"); List <string> comments = CommandProtocol.RecieveList(socket); foreach (string comment in comments) { Console.WriteLine(comment); } } else { Console.WriteLine("Nombre de foto invalido"); } }
private static void ReceivedPackage(object sender, EventArgs e) { CommandPackage package = (CommandPackage)e; Console.WriteLine(Encoding.ASCII.GetString(package.data)); }