C# socket 与网页通讯
class Program
{
static Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //侦听socket
static void Main(string[] args)
{
_socket.Bind(new IPEndPoint(IPAddress.Any, ));
_socket.Listen();
_socket.BeginAccept(new AsyncCallback(OnAccept), _socket); //开始接收来自浏览器的http请求(其实是socket连接请求)
Console.Read();
} static void OnAccept(IAsyncResult ar)
{
try
{
Socket socket = ar.AsyncState as Socket;
Socket new_client = socket.EndAccept(ar); //接收到来自浏览器的代理socket
//NO.1 并行处理http请求
socket.BeginAccept(new AsyncCallback(OnAccept), socket); //开始下一次http请求接收 (此行代码放在NO.2处时,就是串行处理http请求,前一次处理过程会阻塞下一次请求处理) byte[] recv_buffer = new byte[ * ];
int real_recv = new_client.Receive(recv_buffer); //接收浏览器的请求数据
string recv_request = Encoding.UTF8.GetString(recv_buffer, , real_recv);
Console.WriteLine(recv_request); //将请求显示到界面 Resolve(recv_request, new_client); //解析、路由、处理 //NO.2 串行处理http请求
}
catch
{ }
} /// <summary>
/// 按照HTTP协议格式 解析浏览器发送的请求字符串
/// </summary>
/// <param name="request"></param>
/// <param name="response"></param>
static void Resolve(string request, Socket response)
{
//浏览器发送的请求字符串request格式类似这样:
//GET /index.html HTTP/1.1
//Host: 127.0.0.1:8081
//Connection: keep-alive
//Cache-Control: max-age=0
//
//id=123&pass=123 (post方式提交的表单数据,get方式提交数据直接在url中) string[] strs = request.Split(new string[] { "\r\n" }, StringSplitOptions.None); //以“换行”作为切分标志
if (strs.Length > ) //解析出请求路径、post传递的参数(get方式传递参数直接从url中解析)
{
string[] items = strs[].Split(' '); //items[1]表示请求url中的路径部分(不含主机部分)
Dictionary<string, string> param = new Dictionary<string, string>(); if (strs.Contains("")) //包含空行 说明存在post数据
{
string post_data = strs[strs.Length - ]; //最后一项
if (post_data != "")
{
string[] post_datas = post_data.Split('&');
foreach (string s in post_datas)
{
param.Add(s.Split('=')[], s.Split('=')[]);
}
}
}
Route(items[], param, response); //路由处理
}
} /// <summary>
/// 按照请求路径(不包括主机部分) 进行路由处理
/// </summary>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="response"></param>
static void Route(string path, Dictionary<string, string> param, Socket response)
{ Console.WriteLine(path); Home.HomePage(response,path); //if (path.EndsWith("/")) //请求首页
//{
// Home.HomePage(response);
//}
//else if (path.EndsWith("login.zsp")) //登录 处理页面
//{
// //User.LoginCheck(param["id"], param["pass"], response);
//}
////...
} /// <summary>
/// 请求首页
/// </summary>
class Home
{
public static void HomePage(Socket response,string text)
{
string statusline = "HTTP/1.1 200 OK\r\n"; //状态行
byte[] statusline_to_bytes = Encoding.UTF8.GetBytes(statusline); string content =text; byte[] content_to_bytes = Encoding.UTF8.GetBytes(content); string header = string.Format("Content-Type:text/html;charset=UTF-8\r\nContent-Length:{0}\r\n", content_to_bytes.Length);
byte[] header_to_bytes = Encoding.UTF8.GetBytes(header); //应答头 response.Send(statusline_to_bytes); //发送状态行
response.Send(header_to_bytes); //发送应答头
response.Send(new byte[] { (byte)'\r', (byte)'\n' }); //发送空行
response.Send(content_to_bytes); //发送正文(html) response.Close();
}
//...
} }
C# socket 与网页通讯的更多相关文章
- C# Socket的TCP通讯
Socket的TCP通讯 一. socket的通讯原理 服务器端的步骤如下. (1)建立服务器端的Socket,开始侦听整个网络中的连接请求. (2)当检测到来自客户端的连接请求时,向客户端发送收到连 ...
- Android 通过Socket 和服务器通讯
Extends:(http://www.cnblogs.com/likwo/p/3641135.html) Android 通过Socket 和服务器通讯,是一种比较常用的通讯方式,时间比较紧,说下大 ...
- C语言之socket获取网页源码
写爬虫也许你用的是python,类似urlopen(url).read()即可获得普通的网页的源码,或者用的java的网络库加上流操作,或者其他高级语言.但你有没有想过使用C语言来实现呢?我曾经以为用 ...
- 零配置Socket TCP消息通讯服务容器EC
EC全称是elastic communication,是基于c#实现的Socket网络通讯服务容器,支持windows .Net和mono.通过EC容器可以让开发人员在不了解Socket网络通讯知识和 ...
- Windows 和 Linux下使用socket下载网页页面内容(可设置接收/发送超时)的代码
主要难点在于设置recv()与send()的超时时间,具体要注意的事项,请看代码注释部分,下面是代码: #include <stdio.h> #include <sys/types. ...
- [C#]手把手教你打造Socket的TCP通讯连接(一)
本文章将讲解基于TCP连接的Socket通讯,使用Socket异步功能,并且无粘包现象,通过事件驱动使用. 在编写Socket代码之前,我们得要定义一下Socket的基本功能. 作为一个TCP连接,不 ...
- python socket 模拟tcp通讯
对于tcp server 端的创建而言, 分为如下步骤: 1,创建socket对象(socket):其中俩个参数分别为 Address Family(如AF_INET为ipv4),AF_I ...
- C# Socket的TCP通讯 异步 (2015-11-07 10:07:19)转载▼
异步 相对于同步,异步中的连接,接收和发送数据的方法都不一样,都有一个回调函数,就是即使不能连接或者接收不到数据,程序还是会一直执行下去,如果连接上了或者接到数据,程序会回到这个回调函数的地方重新往下 ...
- Socket.io+Nodejs通讯实例
具体源码:Socket 目录结构 D:. │ package.json │ server.js │ └─public index.html socket.io.js 需要的条件 socket.io.j ...
随机推荐
- aws 基于延迟策略配置dns故障切换
前提:由于国内访问首尔地区经常出现不稳定情况,现将请求从nginx(sz)转发到nginx(hk)再转发到首尔地区,在基于不改变nginx(seoul)的配置的前提下,引入aws的延迟策略,同时保证国 ...
- SQL语句规范
SQLStructure Query Language,结构化查询语言 1.规范(1)mysql对于SQL语句不区分大小写,SQL语句关键字尽量大写 show databases;show DataB ...
- 【pytorch】学习笔记(二)- Variable
[pytorch]学习笔记(二)- Variable 学习链接自莫烦python 什么是Variable Variable就好像一个篮子,里面装着鸡蛋(Torch 的 Tensor),里面的鸡蛋数不断 ...
- AppCan调试问题
来源:http://edu.appcan.cn/theVideoMain1.html?chapterId=248_1 第1步, 生成AppCan调试中心 第2步, 启动AppCan调试中心 第3步, ...
- Python 入门 之 反射
Python 入门 之 反射 1.反射 : (自省) 反射主要是指程序可以访问.检测和修改它本身状态或行为的一种能力(自省). Python面向对象中的反射:通过字符串的形式操作对象的相关属性.P ...
- 一般处理程序,ajax
一般处理程序调用session: 在.aspx.cs页中读写Session都是Session["***"]就可以获取或者写入.但是在一般处理程序也就是ashx页面中,再这样写的话, ...
- window10提交代码到码云
1.创建项目文件夹,例如创建一个"爬虫项目码云仓库" 2.进入项目文件夹,在地址栏输入cmd然后回车,这样就在该文件夹打开了终端 3.终端输入git init初始化项目仓库,此时会 ...
- vs编译项目报错:The OutputPath property is not set for this project
今天使用VS2008编译项目时报错: The OutputPath property is not set for this project. Please check to make sure t ...
- nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'enterpriseId' in 'class java.lang.String'
错误信息: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for p ...
- 去掉或修改lightinthebox网址与标题中Wholesale关键词
includes\languages\english.php define('SEO_COMMON_KEYWORDS','Wholesale'); 将里面的Wholesale换成你想显示的词即可.