//构思 // 生成Json格式的返回 //统一Json返回格式,方便使用 public static JObject JResult(string returnCode, string returnMsg)//返回x { ErrorRootobject JMsg = new ErrorRootobject() { ReturnCode = returnCode, msg = returnMsg }; string serial = JsonConvert.SerializeObject(JMsg); JObject result = (JObject)JsonConvert.DeserializeObject(serial); return(result); }
//配置HTTP请求管道 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(LogLevel.Debug); loggerFactory.AddDebug(LogLevel.Debug); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } // app.UseRequestIP();//添加自定义的中间件 app.UseAuthentication(); //添加身份验证中间件 app.UseWebSockets(); //添加webSocket中间件 #if UseOptions #region UseWebSocketsOptions var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseWebSockets(webSocketOptions); #endregion #endif #region AcceptWebSocket app.Use(async(context, next) => { if (context.Request.Path == "/subserver/ws")//这里可以定义路径的格式 { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); var buffer = new byte[1024 * 4]; WebSocketReceiveResult webSocketReceiveResult = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); string restring = Encoding.ASCII.GetString(buffer); JObject jObject = (JObject)JsonConvert.DeserializeObject(restring);//序列化结果 // string PiToken = jObject["PiToken"].ToString(); //验证PiToken string subserverId = jObject["SubserverID"].ToString(); macAvailable = true; ErrorRootobject error = new ErrorRootobject { ReturnCode = "1001", msg = "JSON format error" }; string serial = JsonConvert.SerializeObject(error); result = (JObject)JsonConvert.DeserializeObject(serial); if (macAvailable) { var conn = new MySqlConnection(Configuration.GetConnectionString("DefaultConnection")); conn.Open(); var command = conn.CreateCommand(); string query = "SELECT Username" + " FROM UserToSubserver " + "WHERE SubserverID = '" + subserverId + "'"; command.CommandText = query; DbDataReader BindedReader = await command.ExecuteReaderAsync(); if (BindedReader.HasRows) { //如果查询到被绑定 //我担心会查出一个MAC地址绑定了多个用户的情况 //后期可以设置让MAC地址为主键 BindedReader.Read(); string buser = BindedReader["Username"].ToString(); error.ReturnCode = "1005"; error.msg = " This Subserver is owned by " + buser; serial = JsonConvert.SerializeObject(error); result = (JObject)JsonConvert.DeserializeObject(serial); var buffer1 = Encoding.ASCII.GetBytes(serial); //将 await webSocket.SendAsync(new ArraySegment <byte>(buffer1), webSocketReceiveResult.MessageType, webSocketReceiveResult.EndOfMessage, CancellationToken.None); conn.Close();//关闭连接 //加入到字典中 WebsocketClient.AddToDictionary(subserverId, webSocket); } else { var buffer1 = new byte[1024 * 4]; error.ReturnCode = "1006"; error.msg = " SubserverID is not bound "; serial = JsonConvert.SerializeObject(error); result = (JObject)JsonConvert.DeserializeObject(serial); buffer1 = Encoding.ASCII.GetBytes(serial); //将 int a = result.Count; await webSocket.SendAsync(new ArraySegment <byte>(buffer1), webSocketReceiveResult.MessageType, webSocketReceiveResult.EndOfMessage, CancellationToken.None); } conn.Close(); } //启动监听 await ListenToSubserver(context, webSocket); } else { context.Response.StatusCode = 400; } } else { await next();//调用下一个中间件 } }); #endregion app.UseFileServer();//文件服务器中间件 app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }