不妨参考一下我写的两篇博客:Example: Receive HTTP Post without web form via ASP.Net http://blog.csdn.net/xinyaping/article/details/6270473分布式服务平台的协议设计 http://blog.csdn.net/xinyaping/article/details/6550696我认为这两篇小小的短文加起来刚好就是楼主所要的解决方案。 这是来自我实际的大项目的总结。欢迎前辈指导。
handler.ashx <%@ WebHandler Language="C#" Class="Handler" %>using System; using System.Web; using System.Web.SessionState; using System.Collections; using System.Collections.Generic; public class Handler : IHttpHandler,IRequiresSessionState {
public void ProcessRequest (HttpContext context) { context.Response.ContentType = "Application/json"; string method = context.Request.Params["method"].ToString(); if (context.Session["UserID"] == null) { System.Collections.Hashtable ht = new System.Collections.Hashtable(); ht.Add("temp", "user is null"); context.Response.Write(CreateJsonParams(ht)); }else if (!string.IsNullOrEmpty(method) && method.Equals("OutStorehouseCreate")) { OutStorehouseCreate(context); }else if (!string.IsNullOrEmpty(method) && method.Equals("wzidblur")) { wzidblur(context); }else if (!string.IsNullOrEmpty(method) && method.Equals("slblur")) { slblur(context); } }
所谓Socket客户端访问HTTP server,其实就是客户端访问server相应的端口(比如说默认的web端口80)如果你自己用最原始的方式访问这么一个web url / web service的话,你会得到以http协议封装的数据包,包括http header、http body什么的。然后你自己依据http协议去解析。 如何解析呢?当然你需要查阅rfc文档。。可是实际上你不用这么麻烦,这种事情微软已经替你封装好了你看一下这个类: WebClient Class http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.80%29.aspx并且看例子:using System; using System.Net; using System.IO;public class Test { public static void Main (string[] args) { if (args == null || args.Length == 0) { throw new ApplicationException ("Specify the URI of the resource to retrieve."); } WebClient client = new WebClient (); // Add a user agent header in case the // requested URI contains a query. client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); Stream data = client.OpenRead (args[0]); StreamReader reader = new StreamReader (data); string s = reader.ReadToEnd (); Console.WriteLine (s); data.Close (); reader.Close (); } } WebClient底层当然还是调用的WinSocket进行网络通信,只不过省了你对包进行http协议层面的解析的事情,它已经为你解析好了http header和http body,然后如果http header里面的http statue = 200,说明访问正常。如果访问是正常的,你就可以去http body里面找你要的内容。如果你是按照我所写的两篇博客进行的程序设计,那么http body里面就是用json序列化好的内容。 说了这么多,希望你没晕。其实说的都是基础知识,全都是HTTP协议最基础的知识。还有不懂的话,建议先问问google。
这问题怎么问得这么别扭准确地说,是用C#封装然后用在ASP.Net里面的。 我不准备在这个帖子里做科普如果不了解ASP.Net的话,你应该静下心来看一个ASP.Net系列教程,或者干脆找本书看。1、ASP.Net这项技术本身,就是用来做服务端的。(Web Server / Web service端) 2、你到底要实现什么呀,能说清楚不?
你這個設計指什麼?
然后就是json的处理了
这要看你客户端如何格式化post数据。假设它按照http1.1的post命令的协议,那么服务器端就要使用类似 Request.Form[..]方式。而假设客户端是直接了当地把json串推送,那么服务器端就要直截了当地读取 Request.InputStream 流中的字节,然后转换为json字符串(当然紧接下来通常立即反序列化为服务器内存中的对象来处理)。
不妨参考一下我写的两篇博客:Example: Receive HTTP Post without web form via ASP.Net
http://blog.csdn.net/xinyaping/article/details/6270473分布式服务平台的协议设计
http://blog.csdn.net/xinyaping/article/details/6550696我认为这两篇小小的短文加起来刚好就是楼主所要的解决方案。
这是来自我实际的大项目的总结。欢迎前辈指导。
<%@ WebHandler Language="C#" Class="Handler" %>using System;
using System.Web;
using System.Web.SessionState;
using System.Collections;
using System.Collections.Generic;
public class Handler : IHttpHandler,IRequiresSessionState {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "Application/json";
string method = context.Request.Params["method"].ToString();
if (context.Session["UserID"] == null)
{
System.Collections.Hashtable ht = new System.Collections.Hashtable();
ht.Add("temp", "user is null");
context.Response.Write(CreateJsonParams(ht));
}else if (!string.IsNullOrEmpty(method) && method.Equals("OutStorehouseCreate"))
{
OutStorehouseCreate(context);
}else if (!string.IsNullOrEmpty(method) && method.Equals("wzidblur"))
{
wzidblur(context);
}else if (!string.IsNullOrEmpty(method) && method.Equals("slblur"))
{
slblur(context);
}
}
public bool IsReusable {
get {
return false;
}
}
/// <summary>
/// json
/// </summary>
/// <param name="items"></param>
/// <returns></returns>
private string CreateJsonParams(System.Collections.Hashtable items)
{
string returnStr = "";
foreach (System.Collections.DictionaryEntry item in items)
{
returnStr += "\"" + item.Key.ToString() + "\":\"" + item.Value.ToString().Replace("\"", "\\\"") + "\",";
}
return "{" + returnStr.Substring(0, returnStr.Length - 1) + "}";
}
/// <summary>
/// 根据wzid查询物资
/// </summary>
/// <param name="context"></param>
private void wzidblur(HttpContext context)
{
System.Collections.Hashtable ht = new System.Collections.Hashtable();
string wzid = context.Request["wzid"].ToString().Trim();
string kf = context.Request["kf"].ToString().Trim();
string cl= context.Request["cl"].ToString().Trim();
string temp = "error";
System.Collections.Generic.List<whims.model.Kctz> wzlist = new whims.dal.KctzDal().GetlistforKC("and jcwz.wzid='" + wzid + "' and jcwz.wzclglm='"+cl+"' and kctz.tzkfid='"+kf+"'");
if (wzlist != null && wzlist.Count > 0)
{
whims.model.Kctz tz = wzlist[0];
ht.Add("wzid", tz.jcwz.WZID);
ht.Add("wzmc", tz.jcwz.WZMC);
ht.Add("wzgg", tz.jcwz.WZGGXH);
ht.Add("wzcz", tz.jcwz.WZCZ);
ht.Add("wzdw", tz.jcwz.WZJLDW); if (tz.jcwz.WZDJ == null) tz.jcwz.WZDJ = "";
ht.Add("wzdj", tz.jcwz.WZDJ);
ht.Add("kw", tz.TZKWID);
ht.Add("xtid",tz.jcwz.XTID);
temp = "suc"; } ht.Add("temp", temp);
context.Response.Write(CreateJsonParams(ht));
//context.Response.End();
}
/// <summary>
/// 根据wzid查询物资用户输入的数量 是否可以出库
/// </summary>
/// <param name="context"></param>
private void slblur(HttpContext context)
{
System.Collections.Hashtable ht = new System.Collections.Hashtable();
string wzid = context.Request["wzid"].ToString().Trim();
string sl = context.Request["sl"].ToString().Trim();
string rowCount = context.Request["rowCount"].ToString().Trim();
string kf= context.Request["kf"].ToString().Trim();
string temp = "error";
int zsOrzgTemp = 0;
System.Collections.Generic.List<whims.model.Kctz> wzlist = new whims.dal.KctzDal().GetlistforKC("and kctz.wzid='" + wzid + "' and tzkfid='"+kf+"'");
if (wzlist != null && wzlist.Count > 0)
{
whims.model.Kctz tz = wzlist[0];
decimal tzzgsl=Convert.ToDecimal(tz.TZZGSL);
decimal tzzssl=Convert.ToDecimal(tz.TZZSSL);
decimal tzxyl = Convert.ToDecimal(tz.TZXYL);
decimal requstsl=Convert.ToDecimal(sl);
if (tzxyl <= 0)
{
temp = "bkck";
}
else if (tzzssl>0 && requstsl <= tzzssl)
{
zsOrzgTemp = 1;
temp = "zs";
}
else if (tzzssl>0 && requstsl > tzzssl)
{
zsOrzgTemp = 1;
temp = "zsEnd";
}
else if (tzzgsl>0 && requstsl<=tzzgsl)
{
zsOrzgTemp = 2;
temp = "zg";
}
else if (tzzgsl > 0 && requstsl > tzzgsl)
{
zsOrzgTemp = 2;
temp = "zgEnd";
}
ht.Add("wzid", tz.jcwz.WZID);
ht.Add("zssl", tz.TZZSSL);
ht.Add("zgsl", tz.TZZGSL);
}
ht.Add("rowCount", rowCount);
ht.Add("requstSl", sl);
ht.Add("zsOrzgTemp", zsOrzgTemp);
ht.Add("temp", temp);
context.Response.Write(CreateJsonParams(ht));
//context.Response.End();
}
只要看怎么用就行,不用看内容了json就是一个字符串,咱们把它按一定格式分开,就行,而且前端拿 来的json你可以用request.form[key]这样的形式直接取值的,有一个方法是转换用的
ASP.Net当然通常我们是用IIS来搭建这样的服务器。
我当时用的不是IIS,是Linux + Apache + mod_mono
但是这个代码在Windows + IIS和Linux + Apache + mod_mono上面运行的效果一样,而且代码不需要作任何改动。(充分说明.Net的跨平台特性!)这个是ASP.Net而且我注意到他用的是.ashx,其实我的那个例子原本也应该用.ashx。当时写这个例子之前,我还没怎么用过ASP.Net,之前我一直在做WinForm。
服务器我建议还是直接用Web的,IIS / ASP.Net用socket也行,但是用socket的话服务端就不这么写了。无论用IIS / ASP.Net,还是用socket,客户端的协议都不受影响。(这样是我当时架构时考虑的因素之一)
说明:1、IIS / ASP.Net、socket,这个指服务端
2、客户端协议不受影响,这里指的协议指应用层协议,非通讯协议。
所谓Socket客户端访问HTTP server,其实就是客户端访问server相应的端口(比如说默认的web端口80)如果你自己用最原始的方式访问这么一个web url / web service的话,你会得到以http协议封装的数据包,包括http header、http body什么的。然后你自己依据http协议去解析。
如何解析呢?当然你需要查阅rfc文档。。可是实际上你不用这么麻烦,这种事情微软已经替你封装好了你看一下这个类:
WebClient Class
http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.80%29.aspx并且看例子:using System;
using System.Net;
using System.IO;public class Test
{
public static void Main (string[] args)
{
if (args == null || args.Length == 0)
{
throw new ApplicationException ("Specify the URI of the resource to retrieve.");
}
WebClient client = new WebClient (); // Add a user agent header in case the
// requested URI contains a query. client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); Stream data = client.OpenRead (args[0]);
StreamReader reader = new StreamReader (data);
string s = reader.ReadToEnd ();
Console.WriteLine (s);
data.Close ();
reader.Close ();
}
}
WebClient底层当然还是调用的WinSocket进行网络通信,只不过省了你对包进行http协议层面的解析的事情,它已经为你解析好了http header和http body,然后如果http header里面的http statue = 200,说明访问正常。如果访问是正常的,你就可以去http body里面找你要的内容。如果你是按照我所写的两篇博客进行的程序设计,那么http body里面就是用json序列化好的内容。
说了这么多,希望你没晕。其实说的都是基础知识,全都是HTTP协议最基础的知识。还有不懂的话,建议先问问google。
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspxHttpWebResponse Class
http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.aspxWebRequest Class
http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspxWebResponse Class
http://msdn.microsoft.com/en-us/library/system.net.webresponse.aspx其实我实际工程中用的也不是web client,是HttpWebRequest、HttpWebResponse这4个类,搞清楚它们的功能之后,不要问我哪个好,因为哪个都不错,你觉得哪个方便就用哪个。反正它们底层都是一样的,都是socket。
看到你24楼的问题,哥在风中凌乱了。。
如果你服务器端用的是socket,为啥客户端不也用socket呀当然客户端发送http请求也可以,请问http协议是个啥协议呀,再往下走一层,是不是TCP传输协议?假如你客户端发送http请求,发到服务端的socket端口,服务端就把它当作普通的TCP数据包来接收,可以不可以?接收到了之后你再按照http协议去解析吧。真是,不就是一层封装嘛。
不过这个解析貌似你也不用亲自做了,HttpWebRequest、WebRequest应该已经包含相应的方法了
http://search.china-pub.com/s/?key1=tcp+ip%u534f%u8bae%u8be6%u89e3&type=&pz=1&t=2
TCP/IP详解卷三:TCP事务协议,HTTP,NNTP和UNIX域协议
http://product.china-pub.com/685自己看着办吧不懂网络协议的人,伤不起呀:-)
不过回到问题中来,为啥你服务端用socket客户端却偏偏要用http这种上层协议?
跟服务端在应用层协议上保持一致该多好。
这问题怎么问得这么别扭准确地说,是用C#封装然后用在ASP.Net里面的。
我不准备在这个帖子里做科普如果不了解ASP.Net的话,你应该静下心来看一个ASP.Net系列教程,或者干脆找本书看。1、ASP.Net这项技术本身,就是用来做服务端的。(Web Server / Web service端)
2、你到底要实现什么呀,能说清楚不?
另外, 回复LZ:
先学会socket编程再来进行非语言级的http应用(也就是不用语言提供的http操作类库).否则,那是纸上谈兵. 给你代码你也不理解.
-------------------------------aspx页里面不是有一堆的乱七八糟的东西么.给删光. 黄色标记的头定义别删.然后.cs代码里写上相应的 response.write..... 就可以了.
请注意看,我的code里面有这么一行:Response.ContentType = "text/plain";
http://blog.csdn.net/xinyaping/article/details/6270473 <%@ Page Language="C#" EnableSessionState="false" ResponseEncoding="utf-8" %>
<%@ Import Namespace="System.IO" %>
<%
Stream inputStream = HttpContext.Current.Request.InputStream;
StreamReader reader = new StreamReader(inputStream, System.Text.Encoding.UTF8);
string responseContent = reader.ReadToEnd();
Response.ContentType = "text/plain";
Response.Write(responseContent);
%>