栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

.NET开发从IE浏览器跳转至谷歌浏览器

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.NET开发从IE浏览器跳转至谷歌浏览器

.NET开发从IE浏览器跳转至谷歌浏览器
  • 前言
  • 一、窗体程序核心代码
    • 1.跳转代码


前言

运用C#开发window窗体程序适用于从IE浏览器跳转至谷歌浏览器地址

一、窗体程序核心代码 1.跳转代码

代码如下(示例):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using System.Windows.Forms;

namespace openurl
{
    partial class Form1
    {
        static Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  //侦听socket

        /// 
        /// 必需的设计器变量。
        /// 
        private System.ComponentModel.IContainer components = null;

        /// 
        /// 清理所有正在使用的资源。
        /// 
        /// 如果应释放托管资源,为 true;否则为 false。
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// 
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// 
        private void InitializeComponent()
        {
            //隐藏窗体
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;
            SetVisibleCore(false);

            //暴露Socket以方便浏览器访问
            _socket.Bind(new IPEndPoint(IPAddress.Any, 31685));
            _socket.Listen(1);
            _socket.BeginAccept(new AsyncCallback(OnAccept), _socket);  //开始接收来自浏览器的http请求(其实是socket连接请求)
            Console.Read();
        }
        #endregion

        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[1024 * 640];
                int real_recv = new_client.Receive(recv_buffer);  //接收浏览器的请求数据
                string recv_request = Encoding.UTF8.GetString(recv_buffer, 0, real_recv);
                Console.WriteLine(recv_request);  //将请求显示到界面
                if (!string.IsNullOrEmpty(recv_request.Trim()))
                {
                    //处理请求字符串参数
                    string begin = "GET";
                    string end = "HTTP";
                    int IndexofBegin = recv_request.IndexOf(begin);
                    int IndexofEnd = recv_request.IndexOf(end);
                    string param = recv_request.Substring(IndexofBegin + 4, IndexofEnd - IndexofBegin - 4);
                    Resolve(recv_request, new_client, param);  //解析、路由、处理
                }
            }
            catch(Exception e)
            {
                Console.WriteLine("请求浏览器异常" + MessageBox.Show(e.ToString())); //将请求显示到界面
            }
        }

        /// 
        /// 按照HTTP协议格式 解析浏览器发送的请求字符串
        /// 
        /// 
        /// 
        static void Resolve(string request, Socket response, string recv_params)
        {
            //浏览器发送的请求字符串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[] { "rn" }, StringSplitOptions.None);  //以“换行”作为切分标志
            if (strs.Length > 0)  //解析出请求路径、post传递的参数(get方式传递参数直接从url中解析)
            {
                string[] items = strs[0].Split(' ');  //items[1]表示请求url中的路径部分(不含主机部分)
                Dictionary param = new Dictionary();

                if (strs.Contains(""))  //包含空行  说明存在post数据
                {
                    string post_data = strs[strs.Length - 1]; //最后一项
                    if (post_data != "")
                    {
                        string[] post_datas = post_data.Split('&');
                        foreach (string s in post_datas)
                        {
                            param.Add(s.Split('=')[0], s.Split('=')[1]);
                        }
                    }
                }
                Home.WmsPage(response);
                Process myP = new Process();
                string url = getApplicationByType("url");
                url = url + recv_params;
                string chrome = getApplicationByType("chrome");
                if (!string.IsNullOrEmpty(url.Trim()))
                {
                    if (string.IsNullOrEmpty(chrome.Trim())) 
                    {
                        //进程默认方式打开谷歌浏览器
                        myP.StartInfo.FileName = "chrome.exe";
                        myP.StartInfo.Arguments = url + recv_params;
                        myP.Start();
                    }
                    else
                    {
                        //从配置文件打开谷歌浏览器
                        Process.Start(@chrome, url);
                    }
                }
            }
        }

        //1.从外部读取配置文件中跳转url地址   2.从配置文件中读取谷歌浏览器可执行文件路径地址
        static string getApplicationByType(string type)
        {
            string result = "";
            string[] lines = System.IO.File.ReadAllLines(@"C:luckyunapplication.txt");
            foreach (string line in lines)
            {
                if (line.Contains("url") && type.Equals("url"))
                {
                    result = line.Replace("url=", "");
                    break;
                }

                if (line.Contains("chrome") && type.Equals("chrome")) 
                {
                    result = line.Replace("chrome=","");
                    break;
                }
            }
            return result;
        }

    }

    #region 处理请求 并按照HTTP协议格式发送数据到浏览器
    /// 
    /// 请求首页
    /// 
    class Home
    {
        public static void WmsPage(Socket response)
        {
            string statusline = "HTTP/1.1 200 OKrn";   //状态行
            byte[] statusline_to_bytes = Encoding.UTF8.GetBytes(statusline);

            string content =
            "" +
                //禁止浏览器调用默认favicon.ico页面
                "" + 
                "" +
                    "单点登录跳转页" +
                "" +
                "" +
                   "" +
                       "请在chrome浏览器打开wms系统" +
                   "" +
                "" +
            "";  //内容
            byte[] content_to_bytes = Encoding.UTF8.GetBytes(content);

            string header = string.Format("Content-Type:text/html;charset=UTF-8rnContent-Length:{0}rn", 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();
        }
    }
    #endregion
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/954982.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号