public void Resonse(HttpResponse response, int type, string message) { //设置返回信息 string content = JsonConvert.SerializeObject(new { type = type, message = message }); //构造响应报文 response.SetContent(content); response.Content_Encoding = "utf-8"; response.StatusCode = "200"; response.Content_Type = "text/html;charset=UTF-8"; response.Headers["Server"] = "ExampleServer"; response.Headers["Access-Control-Allow-Origin"] = "*"; response.Headers["Access-Control-Allow-Method"] = "POST,GET"; //发送响应 response.Send(); }
public override void OnGet(HttpRequest request, HttpResponse response) { ///链接形式1:"http://*****:*****@"\").Replace("\\..", "").TrimStart('\\'); //string requestFile = Path.Combine(ServerRoot, requestURL); //判断地址中是否存在扩展名 //string extension = Path.GetExtension(requestFile); //根据有无扩展名按照两种不同链接进行处 // if (extension != "") // { // //从文件中返回HTTP响应 // response = response.FromFile(requestFile); // } // else // { // //目录存在且不存在index页面时时列举目录 // if (Directory.Exists(requestFile) && !File.Exists(requestFile + "\\index.html")) // { // requestFile = Path.Combine(ServerRoot, requestFile); // var content = ListDirectory(requestFile, requestURL); // response = response.SetContent(content, Encoding.UTF8); // response.Content_Type = "text/html; charset=UTF-8"; // } // else // { // //加载静态HTML页面 // requestFile = Path.Combine(requestFile, "index.html"); // response = response.FromFile(requestFile); // response.Content_Type = "text/html; charset=UTF-8"; // } // } response = response.SetContent("Local print server is running...", Encoding.UTF8); response.Content_Type = "text/html; charset=UTF-8"; response.StatusCode = "200"; //发送HTTP响应 response.Send(); }
public override void OnPost(HttpRequest request, HttpResponse response) { //获取客户端传递的参数 string data = request.Params == null ? "" : string.Join(";", request.Params.Select(x => x.Key + x.Value).ToArray()); //设置返回信息 string content = sendData; //构造响应报文 response.SetContent(content); response.Content_Encoding = "utf-8"; response.StatusCode = "200"; response.Content_Type = "text/html; charset=UTF-8"; response.Headers["Server"] = "szzminerServer"; //发送响应 response.Send(); }
public override void OnPost(HttpRequest request, HttpResponse response) { //获取客户端传递的参数 string data = request.Params == null ? "" : string.Join(";", request.Params.Select(x => x.Key + "=" + x.Value).ToArray()); //设置返回信息 string content = string.Format("这是通过Post方式返回的数据:{0}", data); //构造响应报文 response.SetContent(content); response.Content_Encoding = "utf-8"; response.StatusCode = "200"; response.Content_Type = "text/html; charset=UTF-8"; response.Server = "ExampleServer"; //发送响应 response.Send(); }
public override void OnPost(HttpRequest request, HttpResponse response) { //获取客户端传递的参数 //string data = request.Params == null ? "" : string.Join(";", request.Params.Select(x => x.Key + "=" + x.Value).ToArray()); var returnMessage = ""; try { if (this.OnPostRequestReceived == null) { returnMessage = "打印服务器配置不正确,请联系系统管理员"; } else { returnMessage = this.OnPostRequestReceived(request, request.Body); } } catch (Exception ex) { returnMessage = "unhanlded exception :" + ex.Message; } //设置返回信息 string jsonResult = "{\"code\":200, \"msg\":\"" + returnMessage + "\"}"; //构造响应报文 response.SetContent(jsonResult); response.Content_Encoding = "utf-8"; response.StatusCode = "200"; response.Content_Type = "text/json; charset=UTF-8"; response.Headers = new Dictionary <string, string>(); response.SetHeader("Access-Control-Allow-Origin", "*"); //response.SetHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Cookie, Accept"); //response.SetHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, OPTIONS"); //response.SetHeader("Access-Control-Allow-Credentials", "true"); //response.SetHeader("Server", "ExampleServer"); //发送响应 response.Send(); }
public override void OnPost(HttpRequest request, HttpResponse response) { //获取客户端传递的参数 string data = request.Params == null ? "" : string.Join(";", request.Params.Select(x => x.Key + "=" + x.Value).ToArray()); string[] sArray = data.Split(';'); string temp = ""; //Console.WriteLine(data); foreach (string i in sArray) { temp += i; string[] ccc = i.Split('='); if (ccc.Length == 2) { CmdObj.set(ccc[0], ccc[1]); } } //request.Params.Select(x => CmdObj.set(x.Key, x.Value)); //设置返回信息 //string content = string.Format(CmdObj.ToString()); //构造响应报文 Console.WriteLine(CmdObj.toString()); response.SetContent(CmdObj.toString()); response.Content_Encoding = "utf-8"; response.StatusCode = "200"; response.Content_Type = "text/html; charset=UTF-8"; response.Headers["Server"] = "ExampleServer"; response.Headers["Access-Control-Allow-Origin"] = "*"; //发送响应 response.Send(); CmdObj.run(); }
/// <summary> /// Process an incoming request. /// </summary> /// <param name="context">connection to client</param> /// <param name="request">request information</param> /// <param name="response">response that should be filled</param> /// <param name="session">session information</param> protected virtual void HandleRequest(HttpClientContext context, HttpRequest request, HttpResponse response, IHttpSession session) { _logWriter.Write(this, LogPrio.Trace, "Processing request...."); bool handled = false; try { DecodeBody(request); if (ProcessAuthentication(request, response, session)) { foreach (HttpModule module in _modules) { if (!module.Process(request, response, session)) continue; handled = true; if (!module.AllowSecondaryProcessing) break; } } } catch (HttpException err) { if (err.HttpStatusCode == HttpStatusCode.Unauthorized) { AuthenticationModule mod; lock (_authModules) mod = _authModules.Count > 0 ? _authModules[0] : null; if (mod != null) RequestAuthentication(mod, request, response); } else ErrorPage(response, err); } if (!handled && response.Status == HttpStatusCode.OK) ErrorPage(response, HttpStatusCode.NotFound, "Resource not found: " + request.Uri); if (!response.HeadersSent) { // Dispose session if it was not used. if (session.Count > 0) { _sessionStore.Save(session); // only set session cookie if it have not been sent in the request. if (request.Cookies[_sessionCookieName] == null) response.Cookies.Add(new ResponseCookie(_sessionCookieName, session.Id, DateTime.MinValue));//DateTime.Now.AddMinutes(20).AddDays(1))); } else _sessionStore.AddUnused(session); } if (!response.Sent) response.Send(); _logWriter.Write(this, LogPrio.Trace, "....done."); }
void RequestHandler(IHttpClientContext client, IHttpRequest request) { HttpResponse response = new HttpResponse(client, request); // Create a request signature HttpRequestSignature signature = new HttpRequestSignature(request); // Look for a signature match in our handlers for (int i = 0; i < requestHandlers.Length; i++) { HttpRequestHandler handler = requestHandlers[i]; if (handler.Signature != null && signature == handler.Signature) { FireRequestCallback(client, request, response, handler.Callback); return; } } // No registered handler matched this request's signature if (notFoundHandler != null) { FireRequestCallback(client, request, response, notFoundHandler); } else { // Send a default 404 response try { response.Status = HttpStatusCode.NotFound; response.Reason = String.Format("No request handler registered for Method=\"{0}\", Content-Type=\"{1}\", Path=\"{2}\"", signature.Method, signature.ContentType, signature.Path); string notFoundResponse = "<html><head><title>Page Not Found</title></head><body><h3>" + response.Reason + "</h3></body></html>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(notFoundResponse); response.Body.Write(buffer, 0, buffer.Length); response.Send(); } catch (Exception) { } } }
/// <summary> /// Send the response back to the remote client /// </summary> public void Send() { _httpResponse.Body.Flush(); _httpResponse.Send(); }
public override void OnGet(HttpRequest request, HttpResponse response) { ///链接形式1:"http://*****:*****@"\").Replace("\\..", "").TrimStart('\\'); string requestFile = Path.Combine(ServerRoot, requestURL); //Console.WriteLine(request.URL); //判断地址中是否存在扩展名 string extension = Path.GetExtension(requestFile); string[] sArray = request.URL.Split('/'); if (sArray.Length == 3) { CmdObj.setCmd(sArray[1]); CmdObj.setMoney(sArray[2]); CmdObj.run(); } else { Console.WriteLine("参数错误!"); } //根据有无扩展名按照两种不同链接进行处 if (extension != "") { //从文件中返回HTTP响应 //response = response.FromFile(requestFile); response.SetContent("hello1"); } else { //目录存在且不存在index页面时时列举目录 if (Directory.Exists(requestFile) && !File.Exists(requestFile + "\\index.html")) { requestFile = Path.Combine(ServerRoot, requestFile); var content = ListDirectory(requestFile, requestURL); response = response.SetContent(content, Encoding.UTF8); response.Content_Type = "text/html; charset=UTF-8"; } else { //加载静态HTML页面 requestFile = Path.Combine(requestFile, "index.html"); response = response.FromFile(requestFile); response.Content_Type = "text/html; charset=UTF-8"; } } response.Content_Encoding = "utf-8"; response.StatusCode = "200"; response.Content_Type = "text/html; charset=UTF-8"; response.Headers["Server"] = "ExampleServer"; response.Headers["Access-Control-Allow-Origin"] = "*"; response.SetContent(request.URL); //发送HTTP响应 response.Send(); }
public override void OnPost(HttpRequest request, HttpResponse response) { int statusCode = 400; statusCode++; string requestType = ""; string content = ""; if (request == null) { Log("null"); return; } // try //{ //获取客户端传递的参数 requestType = request.Params[@"requestType"]; // 设置返回信息 if (requestType != null && requestType != "") { switch (requestType) { case "GetAGameUser": { string userId = request.Params["userId"]; string userPwd = request.Params["userPwd"]; if (userId != null && userId != "" && userPwd != null && userPwd != "") { GameUser gameUser = DaoFactory.GetGameUserDaoImp().Login(userId, userPwd); if (gameUser != null && gameUser.userId != null && gameUser.userId != "") { content = gameUser.userId + "@@@" + gameUser.userName + "@@@" + gameUser.userPwd; } } } break; case "GetAGamePlayer": { string userId = request.Params["userId"]; if (userId != null && userId != "") { GamePlayer gamePlayer = DaoFactory.GetGamePlayerDaoImp().GetAGamePlayer(userId); if (gamePlayer != null) { content = gamePlayer.userId + "@@@" + gamePlayer.userServer + "@@@" + gamePlayer.playerId + "@@@" + gamePlayer.playerName + "@@@" + gamePlayer.playerLevel + "@@@" + gamePlayer.playerNowExp + "@@@" + gamePlayer.playerUpExp + "@@@" + gamePlayer.playerNowHP + "@@@" + gamePlayer.playerNowMP + "@@@" + gamePlayer.playerMoveSpeed + "@@@" + gamePlayer.playerRunSpeed + "@@@" + gamePlayer.playerElement + "@@@" + gamePlayer.playerMaxHP + "@@@" + gamePlayer.playerMaxMP + "@@@" + gamePlayer.playerAttack + "@@@" + gamePlayer.playerElementHurt + "@@@" + gamePlayer.playerAttackHit + "@@@" + gamePlayer.playerAttackCrit + "@@@" + gamePlayer.playerCritHurt + "@@@" + gamePlayer.playerDefend + "@@@" + gamePlayer.playerAgility + "@@@" + gamePlayer.playerMagicDefend; } } } break; default: Log("参数解析错误"); break; } } //构造响应报文 response.SetContent(content); response.Content_Encoding = "utf-8"; response.StatusCode = statusCode.ToString(); response.Content_Type = "text/html; charset=UTF-8"; response.Headers["Server"] = "ExampleServer"; //发送响应 response.Send(); statusCode++; //} //catch (Exception ex) //{ // Log(ex); //} //finally //{ //} }
public override void OnGet(HttpRequest request, HttpResponse response) { int statusCode = 400; string requestType = ""; string content = ""; try { //获取客户端传递的参数 requestType = request.Params["requestType"]; // 设置返回信息 if (requestType != null && requestType != "") { switch (requestType) { case "LinkServer": { string link = request.Params["link"]; if (link != null && link == "link") { content = "LinkServer Success"; } else { content = "LinkServer Failed"; } } break; case "Login": { string userId = request.Params["userId"]; string userPwd = request.Params["userPwd"]; if (userId != null && userId != "" && userPwd != null && userPwd != "") { GameUser gameUser = DaoFactory.GetGameUserDaoImp().Login(userId, userPwd); if (gameUser != null && gameUser.userId != null) { if (gameUser.userId != "") { content = gameUser.userId + "@@@" + gameUser.userPwd + "@@@" + gameUser.userName; } else { content = "Login Failed"; } } else { content = "Login Failed"; } } } break; case "InsertGameUser": { string userId = request.Params["userId"]; string userPwd = request.Params["userPwd"]; if (userId != null && userId != "" && userPwd != null && userPwd != "") { GameUser gameUser = new GameUser(userId, userPwd, "默认名字"); bool isInsert = DaoFactory.GetGameUserDaoImp().InsertGameUser(gameUser); if (isInsert) { content = "InsertGameUser Success"; } else { content = "InsertGameUser Failed"; } } else { content = "InsertGameUser Failed"; } } break; case "GetAGamePlayer": { string userId = request.Params["userId"]; if (userId != null && userId != "") { GamePlayer gamePlayer = DaoFactory.GetGamePlayerDaoImp().GetAGamePlayer(userId); if (gamePlayer != null && gamePlayer.userId != null) { if (gamePlayer.userId != "") { content = gamePlayer.userId + "@@@" + gamePlayer.userServer + "@@@" + gamePlayer.playerId + "@@@" + gamePlayer.playerPrefabName + "@@@" + gamePlayer.playerName + "@@@" + gamePlayer.playerLevel + "@@@" + gamePlayer.playerNowExp + "@@@" + gamePlayer.playerUpExp + "@@@" + gamePlayer.playerNowHP + "@@@" + gamePlayer.playerNowMP + "@@@" + gamePlayer.playerMoveSpeed + "@@@" + gamePlayer.playerRunSpeed + "@@@" + gamePlayer.playerElement + "@@@" + gamePlayer.playerMaxHP + "@@@" + gamePlayer.playerMaxMP + "@@@" + gamePlayer.playerAttack + "@@@" + gamePlayer.playerElementHurt + "@@@" + gamePlayer.playerAttackHit + "@@@" + gamePlayer.playerAttackCrit + "@@@" + gamePlayer.playerCritHurt + "@@@" + gamePlayer.playerDefend + "@@@" + gamePlayer.playerAgility + "@@@" + gamePlayer.playerMagicDefend; } else { content = "GetAGamePlayer Failed"; } } else { content = "GetAGamePlayer Failed"; } } } break; case "GetGamePlayers": { string userId = request.Params["userId"]; if (userId != null && userId != "") { List <GamePlayer> gamePlayers = DaoFactory.GetGamePlayerDaoImp().GetServerGamePlayer(userId); GamePlayer gamePlayer = DaoFactory.GetGamePlayerDaoImp().GetAGamePlayer(userId); if (gamePlayer != null && gamePlayer.userId != null) { if (gamePlayer.userId != "") { content = gamePlayer.userId + "@@@" + gamePlayer.userServer + "@@@" + gamePlayer.playerId + "@@@" + gamePlayer.playerPrefabName + "@@@" + gamePlayer.playerName + "@@@" + gamePlayer.playerLevel + "@@@" + gamePlayer.playerNowExp + "@@@" + gamePlayer.playerUpExp + "@@@" + gamePlayer.playerNowHP + "@@@" + gamePlayer.playerNowMP + "@@@" + gamePlayer.playerMoveSpeed + "@@@" + gamePlayer.playerRunSpeed + "@@@" + gamePlayer.playerElement + "@@@" + gamePlayer.playerMaxHP + "@@@" + gamePlayer.playerMaxMP + "@@@" + gamePlayer.playerAttack + "@@@" + gamePlayer.playerElementHurt + "@@@" + gamePlayer.playerAttackHit + "@@@" + gamePlayer.playerAttackCrit + "@@@" + gamePlayer.playerCritHurt + "@@@" + gamePlayer.playerDefend + "@@@" + gamePlayer.playerAgility + "@@@" + gamePlayer.playerMagicDefend; } else { content = "GetAGamePlayer Failed"; } } else { content = "GetAGamePlayer Failed"; } } } break; case "GetServerGamePlayer": { string userId = request.Params["userId"]; if (userId != null && userId != "") { List <GamePlayer> gamePlayers = DaoFactory.GetGamePlayerDaoImp().GetServerGamePlayer(userId); if (gamePlayers.Count > 0) { for (int i = 0; i < gamePlayers.Count; i++) { content += gamePlayers[i].userId + "@@@" + gamePlayers[i].userServer + "@@@" + gamePlayers[i].playerId + "@@@" + gamePlayers[i].playerPrefabName + "@@@" + gamePlayers[i].playerName + "@@@" + gamePlayers[i].playerLevel + "@@@" + gamePlayers[i].playerNowExp + "@@@" + gamePlayers[i].playerUpExp + "@@@" + gamePlayers[i].playerNowHP + "@@@" + gamePlayers[i].playerNowMP + "@@@" + gamePlayers[i].playerMoveSpeed + "@@@" + gamePlayers[i].playerRunSpeed + "@@@" + gamePlayers[i].playerElement + "@@@" + gamePlayers[i].playerMaxHP + "@@@" + gamePlayers[i].playerMaxMP + "@@@" + gamePlayers[i].playerAttack + "@@@" + gamePlayers[i].playerElementHurt + "@@@" + gamePlayers[i].playerAttackHit + "@@@" + gamePlayers[i].playerAttackCrit + "@@@" + gamePlayers[i].playerCritHurt + "@@@" + gamePlayers[i].playerDefend + "@@@" + gamePlayers[i].playerAgility + "@@@" + gamePlayers[i].playerMagicDefend + "@@@" + gamePlayers[i].playerGCoins + "@@@" + gamePlayers[i].playerSCoins + "@@@"; } content += gamePlayers.Count.ToString(); } else { content = "GetServerGamePlayer Failed"; } } } break; case "InsertGamePlayer": { string userId = request.Params["userId"]; string userServer = request.Params["userServer"]; string playerId = request.Params["playerId"]; string playerPrefabName = request.Params["playerPrefabName"]; string playerName = request.Params["playerName"]; if (DaoFactory.GetGamePlayerDaoImp().IsExistPlayerName(playerName)) { content = "Duplicate PlayerName"; break; } GamePlayer gamePlayer = null; switch (playerPrefabName) { case "Eri": case "Naoko": case "Riko": gamePlayer = new GamePlayer(userId, userServer, playerId, playerPrefabName, playerName, PlayerBasicData.playerLevel, PlayerBasicData.playerNowExp, PlayerBasicData.playerUpExp, PlayerBasicData.playerNowHP, (int)(PlayerBasicData.playerNowMP * PlayerBasicData.SwordBsic), PlayerBasicData.playerMoveSpeed, PlayerBasicData.playerRunSpeed, PlayerBasicData.playerElement, PlayerBasicData.playerMaxHP, (int)(PlayerBasicData.playerMaxMP * PlayerBasicData.SwordBsic), PlayerBasicData.playerAttack, PlayerBasicData.playerElementHurt, PlayerBasicData.playerAttackHit, PlayerBasicData.playerAttackCrit, PlayerBasicData.playerCritHurt, PlayerBasicData.playerDefend, PlayerBasicData.playerAgility, PlayerBasicData.playerMagicDefend, PlayerBasicData.playerGCoins, PlayerBasicData.playerSCoins); break; case "BladeM": case "BladeW": gamePlayer = new GamePlayer(userId, userServer, playerId, playerPrefabName, playerName, PlayerBasicData.playerLevel, PlayerBasicData.playerNowExp, PlayerBasicData.playerUpExp, (int)(PlayerBasicData.playerNowHP * PlayerBasicData.SwordBsic), PlayerBasicData.playerNowMP, PlayerBasicData.playerMoveSpeed, PlayerBasicData.playerRunSpeed, PlayerBasicData.playerElement, (int)(PlayerBasicData.playerMaxHP * PlayerBasicData.SwordBsic), PlayerBasicData.playerMaxMP, PlayerBasicData.playerAttack, PlayerBasicData.playerElementHurt, PlayerBasicData.playerAttackHit, PlayerBasicData.playerAttackCrit, PlayerBasicData.playerCritHurt, (int)(PlayerBasicData.playerDefend * PlayerBasicData.SwordBsic), (int)(PlayerBasicData.playerAgility * PlayerBasicData.SwordBsic), PlayerBasicData.playerMagicDefend, PlayerBasicData.playerGCoins, PlayerBasicData.playerSCoins); break; } if (userId != null && userId != "") { if (gamePlayer != null) { DaoFactory.GetGamePlayerDaoImp().InsertGamePlayer(gamePlayer); if (gamePlayer.playerId != null && gamePlayer.playerId != "") { content = "InsertGamePlayer Success"; switch (playerPrefabName) { case "Eri": case "Naoko": case "Riko": DaoFactory.GetGameGoodDaoImp().InsertGameGood(GoodBasicData.GetGood_Magic_Weapon_武器(playerId, 0)); break; case "BladeM": case "BladeW": DaoFactory.GetGameGoodDaoImp().InsertGameGood(GoodBasicData.GetGood_Sword_Weapon_武器(playerId, 0)); break; } DaoFactory.GetGameGoodDaoImp().InsertGameGood(GoodBasicData.GetGood_Weapon_首饰(playerId, 1)); DaoFactory.GetGameGoodDaoImp().InsertGameGood(GoodBasicData.GetGood_Consumable_HP(playerId, 2)); DaoFactory.GetGameGoodDaoImp().InsertGameGood(GoodBasicData.GetGood_Consumable_MP(playerId, 3)); DaoFactory.GetGameGoodDaoImp().InsertGameGood(GoodBasicData.GetGood_Armor_上衣(playerId, 4)); } else { content = "InsertGamePlayer Failed"; } } else { content = "InsertGamePlayer Failed"; } } } break; case "DeleteGamePlayer": { string playerId = request.Params["playerId"]; if (playerId != null && playerId != "") { bool isDelete = DaoFactory.GetGamePlayerDaoImp().DeleteGamePlayer(playerId); if (isDelete) { content = "DeleteGamePlayer Success"; DaoFactory.GetGameGoodDaoImp().DeleteGameGood(playerId); } else { content = "DeleteGamePlayer Failed"; } } } break; case "GetAllGamePlayerGameGood": { string playerId = request.Params["playerId"]; List <GameGood> gameGoods = DaoFactory.GetGameGoodDaoImp().GetAllGamePlayerGameGood(playerId); if (playerId != null && playerId != "") { if (gameGoods != null && gameGoods.Count >= 0) { for (int i = 0; i < gameGoods.Count; i++) { content += gameGoods[i].goodId + "@@@" + gameGoods[i].goodName + "@@@" + gameGoods[i].goodDescrip + "@@@" + gameGoods[i].goodBuyPrice + "@@@" + gameGoods[i].goodSellPrice + "@@@" + gameGoods[i].goodIconPath + "@@@" + gameGoods[i].goodItemType + "@@@" + gameGoods[i].goodCount + "@@@" + gameGoods[i].goodType + "@@@" + gameGoods[i].goodEquip + "@@@" + gameGoods[i].ArmorBlood + "@@@" + gameGoods[i].ArmorDefend + "@@@" + gameGoods[i].ArmorAgility + "@@@" + gameGoods[i].ConsumableBcakHP + "@@@" + gameGoods[i].ConsumableBcakMP + "@@@" + gameGoods[i].WeaponDamage + "@@@"; if (i == gameGoods.Count - 1) { content += gameGoods[i].WeaponMP; } else { content += gameGoods[i].WeaponMP + "@@@"; } } } else { content = "GetAllGamePlayerGameGood Failed"; } } else { content = "GetAllGamePlayerGameGood Failed"; } } break; default: Log("参数解析错误"); break; } } StreamWriter sw = new StreamWriter(path, true); sw.WriteLine("[" + DateTime.Now + "] request: " + requestType + " response: " + content); sw.Close(); //构造响应报文 response.SetContent(content); response.Content_Encoding = "utf-8"; response.StatusCode = statusCode.ToString(); response.Content_Type = "text/html; charset=UTF-8"; response.Headers["Server"] = "ExampleServer"; //发送响应 response.Send(); } catch (Exception ex) { Log(ex); } finally { statusCode++; requestType = ""; content = ""; } }
private void binaryHandler(Socket sock) { int maxlen = 1 << 20; // Use a 1MB buffer sock.ReceiveBufferSize = maxlen; byte[] data = new byte[maxlen]; SocketAsyncEventArgs args = new SocketAsyncEventArgs(); do { // Get one request at a time HttpRequest request = new HttpRequest(); int totalread = 0; try { do { // Repetitively read until request is complete if ((totalread + maxlen) > data.Length) { // Enlarge the buffer byte[] newdata = new byte[2 * data.Length]; Array.Copy(data, newdata, data.Length); data = newdata; } args.SetBuffer(data, totalread, data.Length - totalread); // Don't need the return value; we control the buffer. getBytes(sock, maxlen, 120000, args); if (SocketError.Success == args.SocketError) { totalread += args.BytesTransferred; byte[] remainder = request.Continue(data, totalread); // There might be another request, or at least the start of one if (null != remainder) { totalread -= (data.Length - remainder.Length); data = remainder; } else { // No further data, just reset the offset. totalread = 0; } } else { // Some error occurred return; } // Sanity check what we have so far if (HttpVersion.INVALID_VERSION == request.Version) { HttpResponse resp = new HttpResponse( sock, HttpStatusCode.HttpVersionNotSupported, Utility.CONTENT_TYPES[(int)ResponseType.TEXT_PLAIN], "The protocol version specified in the request is not recognized!\n"); // Send the error report, which will close the connection; we don't care what else the client wanted resp.Send(ConnectionPersistence.CLOSE); return; } if (HttpMethod.INVALID_METHOD == request.Method) { HttpResponse resp = new HttpResponse( sock, HttpStatusCode.NotImplemented, Utility.CONTENT_TYPES[(int)ResponseType.TEXT_PLAIN], "The request HTTP verb (method) is not recognized!\n", request.Version); // Send the error report, which will close the connection; we don't care what else the client wanted resp.Send(ConnectionPersistence.CLOSE); return; } } while (!request.Complete); // If we get here, this request is complete (might be more in data) servicer(request, sock); } catch (ProtocolViolationException ex) { if (sock.Connected) { HttpResponse resp = new HttpResponse( sock, HttpStatusCode.BadRequest, Utility.CONTENT_TYPES[(int)ResponseType.TEXT_PLAIN], "Bad request!\n" + ex.ToString()); resp.Send(ConnectionPersistence.CLOSE); } return; } catch (Exception ex) { if (sock.Connected) { HttpResponse resp = new HttpResponse( sock, HttpStatusCode.InternalServerError, Utility.CONTENT_TYPES[(int)ResponseType.TEXT_PLAIN], "Internal Server Error!\n" + ex.ToString() + '\n' + ex.StackTrace); resp.Send(ConnectionPersistence.CLOSE); } return; } } while (sock.Connected); }
/// <summary> /// Called after the client connection is established. Receives client request. /// </summary> /// <param name="sock">Connected TCP socket communicating with client</param> private void handler(Socket sock) { sock.ReceiveBufferSize = (1 << 20); // Use a 1MB buffer String data = ""; do { // Get one request at a time HttpRequest request = new HttpRequest(); try { do { // We need (more) data String newdata = getString(sock); if (null == newdata) { // The connection was closed gracefully return; } data += newdata; // Update/populate the request using the Continue function data = request.Continue(data); // Sanity-check what we've parsed so far if (HttpVersion.INVALID_VERSION == request.Version) { HttpResponse resp = new HttpResponse( sock, HttpStatusCode.HttpVersionNotSupported, Utility.CONTENT_TYPES[(int)ResponseType.TEXT_PLAIN], "The protocol version specified in the request is not recognized!\n"); // Send the error report, which will close the connection; we don't care what else the client wanted resp.Send(); return; } if (HttpMethod.INVALID_METHOD == request.Method) { HttpResponse resp = new HttpResponse( sock, HttpStatusCode.NotImplemented, Utility.CONTENT_TYPES[(int)ResponseType.TEXT_PLAIN], "The request HTTP verb (method) is not recognized!\n", request.Version); // Send the error report, which will close the connection; we don't care what else the client wanted resp.Send(); return; } } while (!request.Complete); // OK *that* request is done now. servicer(request, sock); } catch (ProtocolViolationException ex) { if (sock.Connected) { HttpResponse resp = new HttpResponse( sock, HttpStatusCode.BadRequest, Utility.CONTENT_TYPES[(int)ResponseType.TEXT_PLAIN], "Bad request!\n" + ex.ToString()); resp.Send(); } return; } catch (Exception ex) { if (sock.Connected) { HttpResponse resp = new HttpResponse( sock, HttpStatusCode.InternalServerError, Utility.CONTENT_TYPES[(int)ResponseType.TEXT_PLAIN], "Internal Server Error!\n" + ex.ToString() + '\n' + ex.StackTrace); resp.Send(); } return; } // But, there might have been more than one request in the last packet } while (sock.Connected); }