websocke通讯源码,项目实例,rfid ,商场无人引导系统,源码

来源:互联网 发布:2016流行语言网络语言 编辑:程序博客网 时间:2024/04/29 16:34

前台源码

<html>
<head>
    <meta charset="UTF-8">
    <title>Web sockets test</title>
    <script src="~/Style/Js/jquery-1.8.3.js"></script>
    <script type="text/javascript">
        $(function () {
            (function longPolling() {
                $.ajax({
                    url: "/WebSocket/indexstring",
                    data: { "timed": new Date().getTime() },
                    dataType: "text",
                    cache: false,  //无缓存
                    timeout: 5000,
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $("#state").append("[state: " + textStatus + ", error: " + errorThrown + " ]<br/>");
                        if (textStatus == "timeout") { // 请求超时
                            longPolling(); // 递归调用


                            // 其他错误,如网络错误等
                        } else {
                            longPolling();
                        }
                    },
                    success: function (data, textStatus) {
                        $("#state").append("[state: " + textStatus + ", data: { " + data + "} ]<br/>");
                        if (textStatus == "success") { // 请求成功
                            longPolling();
                        }
                    }
                });
            })();


        });
    </script>
    <script type="text/javascript">
        var socket;
        function connect() {
            var host = "ws://" + $("serverIP").value + ":" + $("serverPort").value + "/"
            socket = new WebSocket(host);
            try {
                socket.onopen = function (msg) {
                    $("btnConnect").disabled = true;
                    alert("连接成功!");
                };
                socket.onmessage = function (msg) {
                    if (typeof msg.data == "string") {
                        displayContent(msg.data);
                    }
                    else {
                        alert("非文本消息");
                    }
                };
                socket.onclose = function (msg) { alert("socket closed!") };
            }
            catch (ex) {
                log(ex);
            }
        }
        function send() {
            var obj = {
                name: 9000,
                default_time: 1,
                keep_time: 2,
                Filtering_time: 3,
                default_mode: 4,
                default_number: 5,
                slot_card_time: '',
                choose_time: 6,
                Expiration_time: 7,
                img_upload_state: 8
            };
            var str = JSON.stringify(obj);


            var msg = str + '\0'
            //var msg = $("sendText").value + '\0'
            socket.send(msg);
        }
        function send1() {
            var objb = {
                name: 9999
            }
            var str = JSON.stringify(objb);
            var msg = str + '\0'
            socket.send(msg);
        }
        window.onbeforeunload = function () {
            try {
                socket.close();
                socket = null;
            }
            catch (ex) {
            }
        };
        function $(id) { return document.getElementById(id); }
        function displayContent(msg) {
            imgpath = "default";
            data = "/Style/Img/" + imgpath + ".jpg";
            $("divimg1").attr("src", data);
        }


        function onkey(event) { if (event.keyCode == 13) { send(); } }


        function SendXHR() {


            imgpath = "default";
            data = "/Style/Img/" + imgpath + ".jpg";
            $("divimg1").attr("src", data);
        }
        window.onload = function () {
            SendXHR();
        }
    </script>
</head>
<body>




    <div id="login">
        <div>
            <input id="serverIP" type="text" placeholder="服务器IP" value="127.0.0.1" autofocus="autofocus" />
            <input id="serverPort" type="text" placeholder="服务器端口" value="9000" />
            <input id="btnConnect" type="button" value="连接" onclick="connect()" />
        </div>
        <div>
            <input id="sendText" type="text" placeholder="发送文本" value="I'm WebSocket Client!" />
            <input id="btnSend" type="button" value="发送" onclick="send()" />
        </div>
        <div>
            <div>
                来自服务端的消息
            </div>
            <textarea id="txtContent" cols="50" rows="10" readonly="readonly"></textarea>
        </div>
    </div>
</body>
</html>





后台源码


using MvcTest.Utilities;
using MvcTestModal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;


namespace MvcTest.Controllers
{
    public class WebSocketController : Controller
    {
        //
        // GET: /WebSocket/
        static AutoResetEvent allDone = new AutoResetEvent(false);
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Test()
        {
            return View();
        }
        public ActionResult WebSocket()
        {
            return View();
        }
        public ActionResult Testyuying()
        {
            return View();
        }


        /// <summary>
        /// 发送HTTP请求
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="param">请求的参数</param>
        /// <returns>请求结果</returns>
        public string request(string url, string param)
        {


            url = "http://apis.baidu.com/apistore/baidutts/tts";
            param = "text=heloyuzhilinctp=1&per=0";
            string strURL = url + '?' + param;
            System.Net.HttpWebRequest request;
            request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            request.Method = "GET";
            // 添加header
            request.Headers.Add("apikey", "c5682670452c7aeee370ee1b09e24e79");
            System.Net.HttpWebResponse response;
            response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.Stream s;
            s = response.GetResponseStream();
            string StrDate = "";
            string strValue = "";
            StreamReader Reader = new StreamReader(s, Encoding.UTF8);
            while ((StrDate = Reader.ReadLine()) != null)
            {
                strValue += StrDate + "\r\n";
            }
            return strValue;
        }


        public int ImgExist(string username, string content)
        {
            int uu = Convert.ToInt32(content);

            string destDirName = System.AppDomain.CurrentDomain.BaseDirectory + "Style\\Img";
            if (!Directory.Exists(destDirName))
            {
                return 0;
            }
            else
            {
                string[] files = Directory.GetFiles(destDirName);
                DirectoryInfo di = new DirectoryInfo(destDirName);
                //  DirectoryInfo dir1 = new DirectoryInfo(files[2]);
                FileInfo[] finfo = di.GetFiles("*.*", SearchOption.AllDirectories);
                for (int i = 0; i < finfo.Length; i++)
                {
                    string[] k = finfo[i].ToString().Split('.');
                    if (k[0] == Convert.ToInt32(content).ToString())
                    {
                        return 1;
                    }
                }
                return 0;
            }
        }
        [HttpPost]
        public ActionResult ImageUpLoad()
        {

            string kanumber = Request["kahaonumber"];
            string b = Request.Form["kahaonumber"];
            //定义错误消息
            string msg = "";
            //接受上传文件
            HttpPostedFileBase hp = Request.Files["upImage"];
            if (hp == null)
            {
                msg = "请选择文件.";
            }


            //string destDirName = System.AppDomain.CurrentDomain.BaseDirectory;
            //获取上传目录 转换为物理路径
            string uploadPath = Server.MapPath("/Style/img/");
            //获取文件名
            string fileName = hp.FileName;
            //获取文件大小
            long contentLength = hp.ContentLength;
            //文件不能大于1M
            if (contentLength > 1024 * 1024)
            {
                msg = "文件大小超过限制要求.";
            }
            if (!checkFileExtension(fileName))
            {
                msg = "文件为不可上传的类型.";
            }
            string[] qq = fileName.Split('.');




            if (qq[qq.Length - 1] == "jpg")
            {
                string fileNamegif = uploadPath + kanumber + ".gif";
                if (qq[0].ToString() == "default")
                {
                    string path = "/Style/img/" + fileName;
                    //保存文件的物理路径
                    string saveFile = uploadPath + fileName;
                    try
                    {
                        //保存文件
                        hp.SaveAs(fileNamegif);
                        hp.SaveAs(saveFile);
                        msg = "/Style/img/" + fileName;
                    }
                    catch
                    {
                        msg = "上传失败.";
                    }
                    return Json(msg);
                }
                else
                {
                    fileName = kanumber + "." + qq[1];
                    string saveFile = uploadPath + fileName;
                    try
                    {
                        //保存文件
                        hp.SaveAs(fileNamegif);
                        hp.SaveAs(saveFile);
                        msg = "/Style/img/" + fileName;
                    }
                    catch
                    {
                        msg = "上传失败.";
                    }
                    return Json(msg);


                }






            }
            else
            {
                string fileNamejpg = uploadPath + kanumber + ".jpg";


                if (qq[0].ToString() == "default")
                {
                    string path = "/Style/img/" + fileName;
                    //保存文件的物理路径
                    string saveFile = uploadPath + fileName;
                    try
                    {
                        //保存文件
                        hp.SaveAs(fileNamejpg);
                        hp.SaveAs(saveFile);
                        msg = "/Style/img/" + fileName;
                    }
                    catch
                    {
                        msg = "上传失败.";
                    }
                    return Json(msg);
                }
                else
                {


                    fileName = kanumber + "." + qq[1];
                    string saveFile = uploadPath + fileName;
                    try
                    {
                        //保存文件
                        hp.SaveAs(fileNamejpg);
                        hp.SaveAs(saveFile);
                        msg = "/Style/img/" + fileName;
                    }
                    catch
                    {
                        msg = "上传失败.";
                    }
                    return Json(msg);


                }


            }
        }


        /// <summary>
        /// 检查文件后缀名是否符合要求
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private bool checkFileExtension(string fileName)
        {
            //获取文件后缀
            string fileExtension = System.IO.Path.GetExtension(fileName);
            if (fileExtension != null)
                fileExtension = fileExtension.ToLower();
            else
                return false;


            if (fileExtension != ".jpg" && fileExtension != ".gif")
                return false;


            return true;
        }






        public JsonResult AddXml()
        {
            if (Request.IsAjaxRequest())
            {
                try
                {
                    var signIn = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Save_xml_canshu>(
                        new System.IO.StreamReader(HttpContext.Request.InputStream).ReadToEnd());
                    string XmlFilePath1 = "Style\\voice\\datalist.xml";


                    string current_choose_time = signIn.choose_time.Trim();
                    int uu = XMLProcess.xml_update(XmlFilePath1, signIn.default_number.Trim(), "choose_time", current_choose_time, "id");
                    return new JsonResult() { Data = 0 };
                }
                catch (Exception)
                {
                    return new JsonResult() { Data = null };
                }
            }
            return new JsonResult() { Data = null };
        }
    }
}



0 0
原创粉丝点击