C# 控制台或者winform程序开启http的监听状态


1
public class THttpListener 2 { 3 HttpListener listerner; 4 /// <summary> 5 /// 6 /// </summary> 7 /// <param name="prefixes">格式 http://*/test/ </param> 8 /// <param name="authent"></param> 9 public THttpListener(string[] prefixes, AuthenticationSchemes authent = AuthenticationSchemes.Anonymous) 10 { 11 listerner = new HttpListener(); 12 listerner.AuthenticationSchemes = authent;//指定身份验证 Anonymous匿名访问 13 foreach (var item in prefixes) 14 { 15 listerner.Prefixes.Add(item); 16 Console.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " : HttpListener:" + item); 17 } 18 } 19 20 public delegate void ResponseEventArges(HttpListenerContext ctx); 21 public event ResponseEventArges ResponseEvent; 22 AsyncCallback ac = null; 23 24 public void Start() 25 { 26 if (!listerner.IsListening) 27 { 28 listerner.Start(); 29 ac = new AsyncCallback(GetContextAsyncCallback); 30 listerner.BeginGetContext(ac, null); 31 Console.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " : Start"); 32 } 33 } 34 35 /// <summary> 36 /// 停止监听服务 37 /// </summary> 38 public void Stop() 39 { 40 listerner.Stop(); 41 } 42 43 /// <summary> 44 /// 收到监听请求回调 45 /// </summary> 46 /// <param name="ia"></param> 47 public void GetContextAsyncCallback(IAsyncResult ia) 48 { 49 if (ia.IsCompleted) 50 { 51 var ctx = listerner.EndGetContext(ia); 52 ctx.Response.StatusCode = 200; 53 if (ResponseEvent != null) 54 { 55 ResponseEvent.BeginInvoke(ctx, null, null); 56 } 57 else 58 { 59 System.IO.BinaryWriter br = new System.IO.BinaryWriter(ctx.Response.OutputStream, new UTF8Encoding()); 60 br.Write("error: 服务器未处理"); 61 ctx.Response.Close(); 62 br.Close(); 63 br.Dispose(); 64 } 65 } 66 listerner.BeginGetContext(ac, null); 67 } 68 69 public Dictionary<string, string> getData(System.Net.HttpListenerContext ctx) 70 { 71 var request = ctx.Request; 72 if (request.HttpMethod == "GET") 73 { 74 return getData(ctx, DataType.Get); 75 } 76 else 77 { 78 return getData(ctx, DataType.Post); 79 } 80 } 81 82 public Dictionary<string, string> getData(System.Net.HttpListenerContext ctx, DataType type) 83 { 84 var rets = new Dictionary<string, string>(); 85 var request = ctx.Request; 86 switch (type) 87 { 88 case DataType.Post: 89 if (request.HttpMethod == "POST") 90 { 91 string rawData; 92 using (var reader = new StreamReader(request.InputStream, request.ContentEncoding)) 93 { 94 rawData = reader.ReadToEnd(); 95 } 96 string[] rawParams = rawData.Split('&'); 97 foreach (string param in rawParams) 98 { 99 string[] kvPair = param.Split('='); 100 string key = kvPair[0]; 101 string value = HttpUtility.UrlDecode(kvPair[1]); 102 rets[key] = value; 103 } 104 } 105 break; 106 case DataType.Get: 107 if (request.HttpMethod == "GET") 108 { 109 string[] keys = request.QueryString.AllKeys; 110 foreach (string key in keys) 111 { 112 rets[key] = request.QueryString[key]; 113 } 114 } 115 break; 116 } 117 return rets; 118 } 119 120 /// <summary> 121 /// 数据提交方式 122 /// </summary> 123 public enum DataType 124 { 125 Post, 126 Get, 127 } 128 129 130 }


测试调用类

 

 1 public class TestHttp
 2     {
 3         THttpListener _HttpListener;
 4         public TestHttp()
 5         {
 6             string[] strUrl = new string[] { "http://*/Test/" };
 7             _HttpListener = new THttpListener(strUrl);
 8             _HttpListener.ResponseEvent += _HttpListener_ResponseEvent;
 9             _HttpListener.Start();
10         }
11 
12         void _HttpListener_ResponseEvent(System.Net.HttpListenerContext ctx)
13         {
14             //直接获取数据
15             Dictionary<string, string> rets = _HttpListener.getData(ctx);
16             //获取get数据
17             Dictionary<string, string> retGets = _HttpListener.getData(ctx, THttpListener.DataType.Get);
18             //获取post数据
19             Dictionary<string, string> retPosts = _HttpListener.getData(ctx, THttpListener.DataType.Post);
20             ResponseWrite(ctx.Request.AcceptTypes[0], "Ret", ctx.Response);
21         }
22 
23         static void ResponseWrite(string type, string msg, System.Net.HttpListenerResponse response)
24         {
25             //使用Writer输出http响应代码
26             using (System.IO.StreamWriter writer = new System.IO.StreamWriter(response.OutputStream, new UTF8Encoding()))
27             {
28                 response.ContentType = type + ";charset=utf-8";
29                 writer.WriteLine(msg);
30                 writer.Close();
31                 response.Close();
32             }
33         }
34     }


当我们在服务程序或者后台程序需要开启对http的监听,来获取提交数据,但是又不能web服务器来挂在的程序,

 

转载于:https://www.cnblogs.com/shizuchengxuyuan/p/4329012.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/420134.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

前端学习(1391):多人管理项目11邮箱地址查询信息

blog.js //管理页面 //展示页面 const express require(express);const admin express.Router();admin.get(/login, (req, res) > {res.render(admin/login) }); admin.get(/user, (req, res) > {res.render(admin/user) }); admin.post(/login, async(req, res) >…

java tea属于红茶吗_什么茶属于红茶类

茶叶在中国的历史已经非常悠久了。相信很多人都喝过红茶&#xff0c;红茶种类还是比较多的&#xff0c;那么知道什么茶属于红茶类吗&#xff1f;平时买回来的红茶该怎么保存比较好呢&#xff1f;什么茶属于红茶类 1、中国的红茶种类还是比较多的。其中滇红&#xff0c;祁红&…

前端学习(1392):多人管理项目12加密

blog.js //管理页面 //展示页面 const express require(express);const admin express.Router();admin.get(/login, (req, res) > {res.render(admin/login) }); admin.get(/user, (req, res) > {res.render(admin/user) }); admin.post(/login, async(req, res) >…

【c++ primer读书笔记】【第2章】变量和基本类型

1、 无符号类型 含有无符号类型的表达式&#xff0c;当一个算式表达式中既有unsigned int&#xff0c;又有int时&#xff0c;int会转化为unsigned int&#xff0c; 如int a-1&#xff0c;unsigned b1&#xff0c;则在我的机器中a*b4294967295。 无符号数不会小于0也关系到循环…

java 注入 循环_spring依赖注入——循环依赖

上一篇博客简单地分析了下依赖注入。但是对于依赖注入的很多细节&#xff0c;都没有深入的分析。这一篇博客会继续分析spring的依赖注入。这篇博客会解决分析getBean缓存时候遗留下来的循环依赖问题。循环依赖分析首先明确下&#xff0c;只有单例情况下&#xff0c;spring才会试…

前端学习(1393):多人管理项目13加密实现

blog.js //管理页面 //展示页面 const express require(express);const admin express.Router();admin.get(/login, (req, res) > {res.render(admin/login) }); admin.get(/user, (req, res) > {res.render(admin/user) }); admin.post(/login, async(req, res) >…

Python的逻辑运算符and小析

近期突然对验证码的识别感兴趣了,然后就研究了一些图像识别和处理的资料,其中有一种图像处理是关于字体的细化和骨架提取的,但是这种算法没有现成的java代码实现,那些号称的java版代码多半都是效果很差或是根本不行的..搜索的途中看到一个用python实现的细化提骨架算法,效果很不…

java二叉树的深度_java 二叉树的最大深度

二叉树的最大深度Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.Note: A leaf is a node with no children.Example:Given binary tree [3,9,20,null,nul…

前端学习(1394):多人管理项目14多人加密使用

users.js // 创建用户集合 // 引入mongoose第三方模块 const mongoose require(mongoose); // 导入bcrypt const bcrypt require(bcrypt); // 引入joi模块 const Joi require(joi); // 创建用户集合规则 const userSchema new mongoose.Schema({username: {type: String,r…

【卡法电子商务】-常用手机屏幕尺寸 ★★★★★

iPhone4/iPhone4s 320 * 372 / 320 * 441 (已隐藏URL与状态栏) iPhone5/iPhone5s 320 * 460 / 320 * 529 (已隐藏URL与状态栏) Note2 360 * 567 (未隐藏URL与状态栏) iPad 3/4 768*928 (未隐藏URL与状态栏) GALAXY SIII 360 * 567 (未隐藏URL与状态栏) 小米2A 360…

java提高篇四_(转)java提高篇(四)-----理解java的三大特性之多态

面向对象编程有三大特性&#xff1a;封装、继承、多态。封装隐藏了类的内部实现机制&#xff0c;可以在不影响使用的情况下改变类的内部结构&#xff0c;同时也保护了数据。对外界而已它的内部细节是隐藏的&#xff0c;暴露给外界的只是它的访问方法。继承是为了重用父类代码。…

前端学习(1395):多人管理项目15建立请求

{{extend ./common/layout.art}}{{block main}}<!-- 子模板的相对路径相对的就是当前文件 因为它是由模板引擎解析的 而不是浏览器 -->{{include ./common/header.art}}<!-- 主体内容 --><div class"content">{{include ./common/aside.art}}<d…

CreateProcess的使用方法

使用编译器vs2008。 第一、第二个參数的使用方法&#xff1a; 样例&#xff1a; 使用ie打开指定的网页。 注意第二个參数是 可运行文件命令行參数 #include "stdafx.h" #include <windows.h> #include <stdio.h> int main(int argc, char* argv[]) { STA…

学生成绩查询java版_学生成绩查询系统,基于ssm的JAVA系统

每天记录学习&#xff0c;每天会有好心情。*^_^*今天记录的项目是学生成绩查询系统&#xff0c;这个项目是这么回事&#xff1a;介绍了在Internet/WWW环境下构建学生成绩查询系统的设计思路与方法 ,阐述了在学生成绩查询系统中的JSP技术和WEB数据库技术的运用 ,描述了学生成绩查…

技术积累

1、TCP/IP HTTP协议 &#xff08;1&#xff09;TCP报文头格式 &#xff08;2&#xff09;TCP连接的建立与终止&#xff0c;三次握手、四次挥手 &#xff08;3&#xff09;TCP的状态转移图 2、UNIX网络编程 &#xff08;1&#xff09;并发服务器&#xff0c;多进程、多线程编程…

前端学习(1397):项目包含的知识点cookie和session2

const express require(express); //创建网站服务器 const app express(); //开放静态资源文件 const path require(path); //引入 const bodyPaser require(body-parser);const session require(express-session); require(./model/connect)//处理post app.use(bodyPase…

jmeter校验结果_Jenkins在实际失败时验证JMeter构建是否成功

我有类似的问题,阻止我.我需要用Jenkins运行我的JMeter测试.但Jenkins验证JMeter构建在实际失败时是否成功.我想知道我做错了什么,以便当断言失败时jmeter不会返回失败.我运行一个调用jMeter的Windows Batch脚本.这是如何做&#xff1a;命令行cd C:\apache-jmeter-3.1\binjmete…

[Unity3D]unity3d5.0简单的调用摄像头

Unity3D中新建一个工程&#xff0c;加一个Plane&#xff0c;新建一个C# 脚本,将这个脚本添加到Plane上&#xff0c;调用摄像头。(如果显示的图片居然是翻转的&#xff0c;Plane的Rotation 值就可以了) 以下是脚本内容&#xff1a; using UnityEngine; using System.Collections…