Websocket实现前后端通讯。asp.net core

1.visual studio 2019创建一个asp.net core 3.0 的项目。在nuget中添加Fleck

Websocket实现前后端通讯。asp.net core_第1张图片

 

2.html端代码

@{
    ViewData["Title"] = "Home Page";
}


   

Welcome


   

Learn about building Web apps with ASP.NET Core.

   
   


   


 

3.controller层代码

using Fleck;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Websocket.Models;

namespace Websocket.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger _logger;

        public HomeController(ILogger logger)
        {
            CsWebsocket();
            _logger = logger;
        }

        public IActionResult Index()
        {
           
            return View(); 
          
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        #region 测试Websocket
        public static void CsWebsocket()
        {
            FleckLog.Level = Fleck.LogLevel.Debug;
            var allSockets = new List();
            var server = new WebSocketServer("ws://127.0.0.1:5001");
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open!");
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    Debug.WriteLine(message);
                    Console.WriteLine(message);
                    allSockets.ForEach(s => s.Send("Echo: " + message));
                };
            });

            //var input = Console.ReadLine();
            //while (input != "exit")
            //{
            //    foreach (var socket in allSockets)
            //    {
            //        socket.Send(input);
            //    }
            //    input = Console.ReadLine();
            //}
        }
        #endregion
    }
}

 4.再加入socket通讯可以实现上位机功能了

你可能感兴趣的:(WebSocket,websocket,asp.net,javascript)