Foros del Web » Programación para mayores de 30 ;) » .NET »

Multi cliente en servidor - WebSocket C#

Estas en el tema de Multi cliente en servidor - WebSocket C# en el foro de .NET en Foros del Web. Hola a todos, espero que estén bien, necesito ayuda urgente: Me pidieron que investigue sobre WebSocket y se necesita que el servidor pueda recibir más ...
  #1 (permalink)  
Antiguo 22/12/2022, 14:25
Avatar de detective_jd  
Fecha de Ingreso: abril-2011
Ubicación: Salto
Mensajes: 437
Antigüedad: 13 años
Puntos: 6
Multi cliente en servidor - WebSocket C#

Hola a todos, espero que estén bien, necesito ayuda urgente: Me pidieron que investigue sobre WebSocket y se necesita que el servidor pueda recibir más de un cliente, pero no sé cómo adaptar el uso de hilos a mi código al cuál colocaré:

Servidor
Código C#:
Ver original
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using System.Threading;
  8.  
  9. namespace Consola
  10. {
  11.     internal class Program
  12.     {
  13.         static List<TcpClient> tcpClients = new List<TcpClient>();
  14.         static void Main(string[] args)
  15.         {
  16.             string ip = "127.0.0.1";
  17.             int port = 8080;
  18.             var server = new TcpListener(IPAddress.Parse(ip), port);
  19.  
  20.             server.Start();
  21.             Console.WriteLine("Server has started on {0}:{1}, Waiting for a connection…", ip, port);
  22.  
  23.             TcpClient client = server.AcceptTcpClient();
  24.             tcpClients.Add(client);
  25.            
  26.             Console.WriteLine("A client connected.");
  27.  
  28.             NetworkStream stream = client.GetStream();
  29.  
  30.             // enter to an infinite cycle to be able to handle every change in stream
  31.             while (true)
  32.             {
  33.                 while (!stream.DataAvailable) ;
  34.                 while (client.Available < 3) ; // match against "get"
  35.  
  36.                 byte[] bytes = new byte[client.Available];
  37.                 stream.Read(bytes, 0, client.Available);
  38.                 string s = Encoding.UTF8.GetString(bytes);
  39.  
  40.                 if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase))
  41.                 {
  42.                     Console.WriteLine("=====Handshaking from client=====\n{0}", s);
  43.  
  44.                     // 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
  45.                     // 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
  46.                     // 3. Compute SHA-1 and Base64 hash of the new value
  47.                     // 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
  48.                     string swk = Regex.Match(s, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
  49.                     string swka = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  50.                     byte[] swkaSha1 = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
  51.                     string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);
  52.  
  53.                     // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
  54.                     byte[] response = Encoding.UTF8.GetBytes(
  55.                         "HTTP/1.1 101 Switching Protocols\r\n" +
  56.                         "Connection: Upgrade\r\n" +
  57.                         "Upgrade: websocket\r\n" +
  58.                         "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n");
  59.  
  60.                     stream.Write(response, 0, response.Length);
  61.                 }
  62.                 else
  63.                 {
  64.                     bool fin = (bytes[0] & 0b10000000) != 0,
  65.                         mask = (bytes[1] & 0b10000000) != 0; // must be true, "All messages from the client to the server have this bit set"
  66.                     int opcode = bytes[0] & 0b00001111, // expecting 1 - text message
  67.                         offset = 2;
  68.                     ulong msglen = (ulong)(bytes[1] & 0b01111111);
  69.  
  70.                     if (msglen == 126)
  71.                     {
  72.                         // bytes are reversed because websocket will print them in Big-Endian, whereas
  73.                         // BitConverter will want them arranged in little-endian on windows
  74.                         msglen = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
  75.                         offset = 4;
  76.                     }
  77.                     else if (msglen == 127)
  78.                     {
  79.                         // To test the below code, we need to manually buffer larger messages — since the NIC's autobuffering
  80.                         // may be too latency-friendly for this code to run (that is, we may have only some of the bytes in this
  81.                         // websocket frame available through client.Available).
  82.                         msglen = BitConverter.ToUInt64(new byte[] { bytes[9], bytes[8], bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2] }, 0);
  83.                         offset = 10;
  84.                     }
  85.  
  86.                     if (msglen == 0)
  87.                     {
  88.                         Console.WriteLine("msglen == 0");
  89.                     }
  90.                     else if (mask)
  91.                     {
  92.                         byte[] decoded = new byte[msglen];
  93.                         byte[] masks = new byte[4] { bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] };
  94.                         offset += 4;
  95.  
  96.                         for (ulong i = 0; i < msglen; ++i)
  97.                             decoded[i] = (byte)(bytes[(ulong)offset + i] ^ masks[i % 4]);
  98.  
  99.                         string text = Encoding.UTF8.GetString(decoded);
  100.                         Console.WriteLine("{0}", text);
  101.                     }
  102.                     else
  103.                         Console.WriteLine("mask bit not set");
  104.  
  105.                     Console.WriteLine();
  106.                 }
  107.             }
  108.         }
  109.     }
  110. }

Cliente
Código HTML:
Ver original
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <link href="Content/bootstrap.min.css" type="text/css" rel="stylesheet" />    
  4.     <script src="Scripts/jquery-3.6.1.min.js" type="text/javascript"></script>    
  5. </head>
  6.  
  7.     <div class="card">
  8.         <div class="card-header">
  9.             <h2>Prueba multi cliente con WebSocket</h2>
  10.         </div>
  11.         <div class="card-body">
  12.             <p>
  13.                 <textarea cols="60" rows="6" id="cajadetexto"></textarea>
  14.             </p>
  15.             <p>
  16.                 <button id="boton" class="btn btn-primary">Enviar</button>
  17.             </p>
  18.             <p>
  19.                 <div id="salida"></div>
  20.             </p>
  21.         </div>
  22.     </div>
  23.  
  24.     <style type="text/css">
  25.         textarea {
  26.             vertical-align: bottom;
  27.         }
  28.  
  29.         #salida {
  30.             overflow: auto;
  31.         }
  32.  
  33.         #salida > p {
  34.             overflow-wrap: break-word;
  35.         }
  36.  
  37.         #salida span {
  38.             color: blue;
  39.         }
  40.  
  41.         #salida span.error {
  42.             color: red;
  43.         }
  44.     </style>
  45.  
  46.     <script type="text/javascript">
  47.         $(document).ready(function () {
  48.             const wsUri = "ws://127.0.0.1:8080/";
  49.             const websocket = new WebSocket(wsUri);
  50.  
  51.             $(document).on("click", "#boton", onClickButton);
  52.  
  53.             websocket.onopen = (e) => {
  54.                 writeToScreen("CONNECTED");
  55.                 doSend("WebSocket rocks");
  56.             };
  57.  
  58.             websocket.onclose = (e) => {
  59.                 writeToScreen("DISCONNECTED");
  60.             };
  61.  
  62.             websocket.onmessage = (e) => {
  63.                 writeToScreen(`<span>RESPONSE: ${e.data}</span>`);
  64.             };
  65.  
  66.             websocket.onerror = (e) => {
  67.                 writeToScreen(`<span class="error">ERROR:</span> ${e.data}`);
  68.             };
  69.  
  70.             function doSend(message) {
  71.                 writeToScreen(`SENT: ${message}`);
  72.                 websocket.send(message);
  73.             }
  74.  
  75.             function writeToScreen(message) {
  76.                 $("#salida").append("<p>" + message + "</p>");
  77.             }
  78.  
  79.             function onClickButton() {
  80.                 var text = $("#cajadetexto").val();
  81.  
  82.                 text && doSend(text);
  83.                 $("#cajadetexto").val("");
  84.                 $("#cajadetexto").focus();
  85.             }
  86.         });
  87.     </script>
  88. </body>
  89. </html>

Necesito que el cliente se ejecuta en un proyecto web mientras que el servidor en un proyecto de consola.
Intenté de todo, pero lo que obtuve fue lo de la imagen:



Espero sus respuestas y saludos.
__________________
Si te interesa, visita mi perfil de Linkedin. Gracias

Etiquetas: cliente, multi, servidor
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 07:13.