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通讯可以实现上位机功能了