<repo_name>renato-castillo/example-socket<file_sep>/README.md
# example-socket
Ejemplo de servidor websocket en c# y cliente en angular
<file_sep>/web/src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { webSocket, WebSocketSubject } from "rxjs/webSocket";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  subject: WebSocketSubject<unknown> | null = null;

  title = 'web';

  mensaje = '';

  ngOnInit(): void {

    this.subject = webSocket('ws://localhost:9000');

    this.subject.subscribe(
      msg => {
        console.log('message received: ' + (msg as any).mensaje)
      }, // Called whenever there is a message from the server.
      err => {
        console.log(err)
      }, // Called if at any point WebSocket API signals some kind of error.
      () => {
        console.log('complete')
      }// Called when connection is closed (for whatever reason).
    );
    // Note that at least one consumer has to subscribe to the created subject - otherwise "nexted" values will be just buffered and not sent,
    // since no connection was established!

    //this.subject.next({message: 'some message'});
    // This will send a message to the server once a connection is made. Remember value is serialized with JSON.stringify by default!

    //this.subject.complete(); // Closes the connection.

    //this.subject.error({code: 4000, reason: 'I think our app just broke!'});
    // Also closes the connection, but let's the server know that this closing is caused by some error.

  }


  enviar() {
    if (this.subject) {
      this.subject.next({message: this.mensaje});
    }
  }

  desconectar() {
    if (this.subject) {
      this.subject.complete();
    }
  }

}
<file_sep>/server/Program.cs
﻿using System;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using WatsonWebsocket;

namespace server
{
    class Program
    {

        static WatsonWsServer server = new WatsonWsServer("localhost", 9000, false);

        static async Task Main(string[] args)
        {
            server.ClientConnected += ClientConnectedAsync;
            server.ClientDisconnected += ClientDisconnected;
            server.MessageReceived += MessageReceived; 
            await server.StartAsync();
            
            Console.WriteLine("Server is listening: " + server.IsListening);

            while (true) {} // Para que no finalice la apliación

            static void ClientConnectedAsync(object sender, ClientConnectedEventArgs args) 
            {
                Console.WriteLine("Client connected: " + args.IpPort);
                
                // Le respondo al cliente que se conecto al servidor
                string data = JsonSerializer.Serialize(new { mensaje = "Conectado al servidor" });
                server.SendAsync(args.IpPort, data);
            }

            static void ClientDisconnected(object sender, ClientDisconnectedEventArgs args) 
            {
                Console.WriteLine("Client disconnected: " + args.IpPort);
            }

            static void MessageReceived(object sender, MessageReceivedEventArgs args) 
            { 
                // Proceso el mensaje recibido
                string mensaje = Encoding.UTF8.GetString(args.Data);
                Console.WriteLine("Message received from " + args.IpPort + ": " + mensaje);

                // Respondo al cliente lo mismo que recibí
                string data = JsonSerializer.Serialize(new { mensaje = "Recibi esto: " + mensaje});
                server.SendAsync(args.IpPort, data);
            }


        }
    }
}
