一、前端代码:
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> </head> <body> <input type="button" id="send" onclick="send()" value="发送"> <input type="text" id="message"> <script type="text/javascript"> var socket; if (typeof (WebSocket) == "undefined") { alert("您的浏览器不支持WebSocket"); } /* 在websocket中有两个方法: 1、send() 向远程服务器发送数据 2、close() 关闭该websocket链接 */ /*websocket同时还定义了几个监听函数 1、onopen 当网络连接建立时触发该事件 2、onerror 当网络发生错误时触发该事件 3、onclose 当websocket被关闭时触发该事件 4、onmessage 当websocket接收到服务器发来的消息的时触发的事件,也是通信中最重要的一个监听事件。msg.data */ var socket = new WebSocket('ws://localhost:52992/ws'); //打开事件 socket.onopen = function (e) { alert("Socket 已打开"); console.log("Connected!"); } socket.onclose = function (e) { alert("Socket 已关闭"); console.log("Disconnected!"); } socket.onmessage = function (e) { alert("Socket 发送消息"); console.log("接收消息:" + e.data); } socket.onerror = function (e) { alert("Socket 网络发生错误"); console.log(e.data); } //function send() { // var oText = document.getElementById("message"); // socket.send(oText.value); //} //不可以自定 function send() { var otext = document.getElementById("message"); socket.send("SendMessage",otext.value); } socket.receivemessage = function (e) { alert("socket 发送消息"); console.log("接收消息:" + e.data); } </script> </body> </html>
Startup配置:
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; using test.Hubs; //3、引用 处理客户端 - 服务器通信的高级管道 namespace test { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddSignalR();//1、添加服务 } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } //跨域 app.UseCors(builder => { builder.SetIsOriginAllowed(origin => true) .AllowAnyHeader() .WithMethods("GET", "POST") .AllowCredentials(); }); //静态资源 app.UseStaticFiles(); //cookie app.UseCookiePolicy(); //1、配置WebSocket中间件 app.UseWebSockets(); //2、检查它是否是 WebSocket 请求并接受 WebSocket 请求。 app.Use(async (context, next) => { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Echo(context, webSocket); } else { context.Response.StatusCode = 400; } } else { await next(); } }); //配置signalr路径 //app.UseSignalR(routes => //2、引用 //{ // routes.MapHub<ChatHub>("/chatHub"); //}); //mvc模式 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } #region Echo private async Task Echo(HttpContext context, WebSocket webSocket) { var buffer = new byte[1024 * 4]; WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); while (!result.CloseStatus.HasValue) { await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); } #endregion } }
注意:暂时没有办法定义方法