From 7ae3b6c3c16ee7f68a6d3cc4757b471cdf5d7882 Mon Sep 17 00:00:00 2001 From: juanjo Date: Fri, 27 Oct 2023 13:00:37 +0200 Subject: [PATCH] 08 ServidorPPTSondeo --- .../08-ServidorPPTSondeo.csproj | 84 ++++++++ 08-ServidorPPTSondeo/App.config | 6 + 08-ServidorPPTSondeo/Form1.Designer.cs | 61 ++++++ 08-ServidorPPTSondeo/Form1.cs | 198 ++++++++++++++++++ 08-ServidorPPTSondeo/Form1.resx | 120 +++++++++++ 08-ServidorPPTSondeo/Program.cs | 22 ++ .../Properties/AssemblyInfo.cs | 36 ++++ .../Properties/Resources.Designer.cs | 63 ++++++ .../Properties/Resources.resx | 117 +++++++++++ .../Properties/Settings.Designer.cs | 26 +++ .../Properties/Settings.settings | 7 + 11 files changed, 740 insertions(+) create mode 100644 08-ServidorPPTSondeo/08-ServidorPPTSondeo.csproj create mode 100644 08-ServidorPPTSondeo/App.config create mode 100644 08-ServidorPPTSondeo/Form1.Designer.cs create mode 100644 08-ServidorPPTSondeo/Form1.cs create mode 100644 08-ServidorPPTSondeo/Form1.resx create mode 100644 08-ServidorPPTSondeo/Program.cs create mode 100644 08-ServidorPPTSondeo/Properties/AssemblyInfo.cs create mode 100644 08-ServidorPPTSondeo/Properties/Resources.Designer.cs create mode 100644 08-ServidorPPTSondeo/Properties/Resources.resx create mode 100644 08-ServidorPPTSondeo/Properties/Settings.Designer.cs create mode 100644 08-ServidorPPTSondeo/Properties/Settings.settings diff --git a/08-ServidorPPTSondeo/08-ServidorPPTSondeo.csproj b/08-ServidorPPTSondeo/08-ServidorPPTSondeo.csproj new file mode 100644 index 0000000..75d2f45 --- /dev/null +++ b/08-ServidorPPTSondeo/08-ServidorPPTSondeo.csproj @@ -0,0 +1,84 @@ + + + + + Debug + AnyCPU + {52F445E8-27E3-42F1-9088-1FFB4B51EDA8} + WinExe + _08_ServidorPPTSondeo + 08-ServidorPPTSondeo + v4.7.2 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Form + + + Form1.cs + + + + + Form1.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + \ No newline at end of file diff --git a/08-ServidorPPTSondeo/App.config b/08-ServidorPPTSondeo/App.config new file mode 100644 index 0000000..56efbc7 --- /dev/null +++ b/08-ServidorPPTSondeo/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/08-ServidorPPTSondeo/Form1.Designer.cs b/08-ServidorPPTSondeo/Form1.Designer.cs new file mode 100644 index 0000000..cfcc0b7 --- /dev/null +++ b/08-ServidorPPTSondeo/Form1.Designer.cs @@ -0,0 +1,61 @@ +namespace _08_ServidorPPTSondeo +{ + partial class Form1 + { + /// + /// Variable del diseñador necesaria. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Limpiar los recursos que se estén usando. + /// + /// true si los recursos administrados se deben desechar; false en caso contrario. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Código generado por el Diseñador de Windows Forms + + /// + /// Método necesario para admitir el Diseñador. No se puede modificar + /// el contenido de este método con el editor de código. + /// + private void InitializeComponent() + { + this.button1 = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(284, 183); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(232, 84); + this.button1.TabIndex = 1; + this.button1.Text = "Conectar Servidor PPT"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.Button1_Click); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Button button1; + } +} + diff --git a/08-ServidorPPTSondeo/Form1.cs b/08-ServidorPPTSondeo/Form1.cs new file mode 100644 index 0000000..6050d52 --- /dev/null +++ b/08-ServidorPPTSondeo/Form1.cs @@ -0,0 +1,198 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; + + +namespace _08_ServidorPPTSondeo +{ + public partial class Form1 : Form + { + Object o = new object(); //para hacer lock + + string jugador1 = ""; //nick + string idJug1 = ""; //referencia IP:port + string jugada1 = ""; //piedra/papel/tijera + int puntos1 = 0; + string jugador2 = ""; //nick + string idJug2 = ""; //referencia IP:port + string jugada2 = ""; //piedra/papel/tijera + int puntos2 = 0; + + //datos para almacenar jugadas y resultados + int numJugada = 1; //índice de la jugada en curso + string[] textoVueltaJugada = new string[100]; //guarda resultado jugadas (histórico) + + public Form1() + { + InitializeComponent(); + } + + private void ManejarCliente(TcpClient cli) + { + string data; + NetworkStream ns = cli.GetStream(); + StreamReader sr = new StreamReader(ns); + StreamWriter sw = new StreamWriter(ns,Encoding.UTF8); //para ñ y acentos (no funciona con telnet, solo clientes .net) + + //informe de protocolo + sw.WriteLine("#INSCRIBIR#nombre#"); + sw.WriteLine("#JUGADA#{piedra|papel|tijera}#"); + sw.WriteLine("#RESULTADOJUGADA#numeroJugada#"); + sw.WriteLine("#PUNTUACION#"); + sw.Flush(); + + //escucha infinita de peticiones enviadas desde el cliente + while (true) + { + try + { + data = sr.ReadLine(); //linea bloqueante + Debug.WriteLine(data); + String[] subdatos = data.Split('#'); + #region comINSCRIBIR + if (subdatos[1] == "INSCRIBIR") + { + if (jugador1 == "") + { + jugador1 = subdatos[2]; + this.idJug1 = cli.Client.RemoteEndPoint.ToString(); + sw.WriteLine("#OK#"); + sw.Flush(); + } + else if (jugador2 == "") + { + jugador2 = subdatos[2]; + this.idJug2 = cli.Client.RemoteEndPoint.ToString(); + sw.WriteLine("#OK#"); + sw.Flush(); + } + else + { + sw.WriteLine("#NOK#ya hay dos jugadores#"); + sw.Flush(); + } + } + #endregion + #region comJUGADA + if (subdatos[1] == "JUGADA") + { + if ((subdatos[2] != "piedra") && (subdatos[2] != "papel") && (subdatos[2] != "tijera")) + { + sw.WriteLine("#NOK#valores válido: piedra/papel/tijera#"); + sw.Flush(); + } + //comprobar quien hace la jugada + else if ((idJug1 == cli.Client.RemoteEndPoint.ToString()) || + (idJug2 == cli.Client.RemoteEndPoint.ToString())) + { + if (idJug1 == cli.Client.RemoteEndPoint.ToString()) + { //estamos en el jugador 1 + jugada1 = subdatos[2]; + + } + else + { //estamos en el jugador2 + jugada2 = subdatos[2]; + + } + sw.WriteLine("#OK#" + this.numJugada + "#"); + sw.Flush(); + + lock (o) //solo uno puede comprobar + { + //comprobar si tengo emitidas el par de jugadas + if (jugada1 != "" && jugada2 != "") + { + CompruebaGanador(); + this.numJugada++; //pasamos a la siguiente jugada + this.jugada1 = ""; + this.jugada2 = ""; + } + } + } + } + #endregion + #region comRESULTADOJUGADA + if (subdatos[1] == "RESULTADOJUGADA") + { + int numJugadaCliente = System.Convert.ToInt32(subdatos[2]); + if ((numJugadaCliente > 0) && (numJugadaCliente < this.numJugada)) + { + sw.WriteLine(this.textoVueltaJugada[numJugadaCliente - 1]); + sw.Flush(); + } + else + { + sw.WriteLine("#NOK#número de jugada no válido#"); + sw.Flush(); + } + } + #endregion + #region comPUNTUACION + if (subdatos[1] == "PUNTUACION") + { + sw.WriteLine("#OK#" + jugador1 + ":" + puntos1.ToString() + "#" + + jugador2 + ":" + puntos2.ToString() + "#"); + sw.Flush(); + } + #endregion + } + catch (Exception error) + { + Debug.WriteLine("Error: " + error.ToString()); + } //end catch + } //end while + } //end metodo + + private void Button1_Click(object sender, EventArgs e) + { + TcpListener newsock = new TcpListener(IPAddress.Any, 2000); + newsock.Start(); + + //escucha infinita de clientes que se quieran conecar + while (true) + { + TcpClient client = newsock.AcceptTcpClient(); //linea bloquente + Thread t = new Thread(() => this.ManejarCliente(client)); + t.Start(); + } + } + + private void CompruebaGanador() + { + //resolver la jugada + //gana el 1 + if ((jugada1 == "piedra" && jugada2 == "tijera") || + (jugada1 == "tijera" && jugada2 == "papel") || + (jugada1 == "papel" && jugada2 == "piedra")) + { + this.textoVueltaJugada[numJugada - 1] = "#OK#GANDOR:" + this.jugador1 + "#"; + puntos1++; + } + //gana el 2 + else if ((jugada2 == "piedra" && jugada1 == "tijera") || + (jugada2 == "tijera" && jugada1 == "papel") || + (jugada2 == "papel" && jugada1 == "piedra")) + { + this.textoVueltaJugada[numJugada - 1] = "#OK#GANDOR:" + this.jugador2 + "#"; + puntos2++; + } + //empate + else + { + this.textoVueltaJugada[numJugada - 1] = "#OK#EMPATE#"; + } + } + } +} diff --git a/08-ServidorPPTSondeo/Form1.resx b/08-ServidorPPTSondeo/Form1.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/08-ServidorPPTSondeo/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/08-ServidorPPTSondeo/Program.cs b/08-ServidorPPTSondeo/Program.cs new file mode 100644 index 0000000..3e0004e --- /dev/null +++ b/08-ServidorPPTSondeo/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace _08_ServidorPPTSondeo +{ + static class Program + { + /// + /// Punto de entrada principal para la aplicación. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/08-ServidorPPTSondeo/Properties/AssemblyInfo.cs b/08-ServidorPPTSondeo/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..44b9c48 --- /dev/null +++ b/08-ServidorPPTSondeo/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// La información general de un ensamblado se controla mediante el siguiente +// conjunto de atributos. Cambie estos valores de atributo para modificar la información +// asociada con un ensamblado. +[assembly: AssemblyTitle("11-ServidorPPTSondeo")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("11-ServidorPPTSondeo")] +[assembly: AssemblyCopyright("Copyright © 2020")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles +// para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde +// COM, establezca el atributo ComVisible en true en este tipo. +[assembly: ComVisible(false)] + +// El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM. +[assembly: Guid("52f445e8-27e3-42f1-9088-1ffb4b51eda8")] + +// La información de versión de un ensamblado consta de los cuatro valores siguientes: +// +// Versión principal +// Versión secundaria +// Número de compilación +// Revisión +// +// Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión +// utilizando el carácter "*", como se muestra a continuación: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/08-ServidorPPTSondeo/Properties/Resources.Designer.cs b/08-ServidorPPTSondeo/Properties/Resources.Designer.cs new file mode 100644 index 0000000..2aaf0c3 --- /dev/null +++ b/08-ServidorPPTSondeo/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// Este código fue generado por una herramienta. +// Versión de runtime:4.0.30319.42000 +// +// Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si +// se vuelve a generar el código. +// +//------------------------------------------------------------------------------ + +namespace _08_ServidorPPTSondeo.Properties { + using System; + + + /// + /// Clase de recurso fuertemente tipado, para buscar cadenas traducidas, etc. + /// + // StronglyTypedResourceBuilder generó automáticamente esta clase + // a través de una herramienta como ResGen o Visual Studio. + // Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen + // con la opción /str o recompile su proyecto de VS. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Devuelve la instancia de ResourceManager almacenada en caché utilizada por esta clase. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("_08_ServidorPPTSondeo.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Reemplaza la propiedad CurrentUICulture del subproceso actual para todas las + /// búsquedas de recursos mediante esta clase de recurso fuertemente tipado. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/08-ServidorPPTSondeo/Properties/Resources.resx b/08-ServidorPPTSondeo/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/08-ServidorPPTSondeo/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/08-ServidorPPTSondeo/Properties/Settings.Designer.cs b/08-ServidorPPTSondeo/Properties/Settings.Designer.cs new file mode 100644 index 0000000..f86638d --- /dev/null +++ b/08-ServidorPPTSondeo/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// Este código fue generado por una herramienta. +// Versión de runtime:4.0.30319.42000 +// +// Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si +// se vuelve a generar el código. +// +//------------------------------------------------------------------------------ + +namespace _08_ServidorPPTSondeo.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.10.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/08-ServidorPPTSondeo/Properties/Settings.settings b/08-ServidorPPTSondeo/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/08-ServidorPPTSondeo/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + +