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

本文介绍了如何在Visual Studio 2019中创建一个ASP.NET Core 3.0项目,并通过NuGet添加Fleck库来实现WebSocket通信。在HTML端,展示了用于发送和接收消息的输入框、按钮和预览区域。在控制器层,利用Fleck库设置WebSocket服务器并处理客户端连接、消息收发。这个示例展示了如何构建一个简单的上位机功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

2.html端代码

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

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>

    <input id="sendText" placeholder="Text to send" />
    <pre id="incomming"></pre>
    <button οnclick="send()">send</button>
</div>

<script type="text/javascript">
        var start = function () {
            var inc = document.getElementById('incomming');
            var wsImpl = window.WebSocket || window.MozWebSocket;
            var form = document.getElementById('sendForm');
            var input = document.getElementById('sendText');

            inc.innerHTML += "connecting to server ..<br/>";

            // 创建新的websocket新连接端口为7181
            window.ws = new wsImpl('ws://127.0.0.1:5001/');

            // 当数据从服务器服务中心发送后,继续向下运行过程
            ws.onmessage = function (evt) {
                inc.innerHTML += evt.data + '<br/>';
            };

            // 当链接对象找到服务端成功对接后,提示正常打开
            ws.onopen = function () {
                inc.innerHTML += '.. connection open<br/>';
            };

            // 当链接对象未找找到服务端成功对接后,提示打开失败,别切单项关闭
            ws.onclose = function () {
                inc.innerHTML += '.. connection closed<br/>';
            }

            //form.addEventListener('submit', function (e) {
            //    e.preventDefault();
            //    var val = input.value;
            //    ws.send(val);
            //    input.value = "";
            //});

        }
    window.onload = start;

    function send() {
        var input = document.getElementById('sendText');
        var val = input.value;
               ws.send(val);
    }
</script>
 

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<HomeController> _logger;

        public HomeController(ILogger<HomeController> 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<IWebSocketConnection>();
            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通讯可以实现上位机功能了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值