H5WebSocket消息推送


1、效果圖

2、前端代碼

@{
    ViewBag.Title = "Home Page";
}


    @*HTML5 WebSocket
WebSocket是HTML5開始提供的一種在單個 TCP 連接上進行全雙工通訊的協議。
在WebSocket API中,瀏覽器和服務器只需要做一個握手的動作,然后,瀏覽器和服務器之間就形成了一條快速通道。兩者之間就直接可以數據互相傳送。
瀏覽器通過 JavaScript 向服務器發出建立 WebSocket 連接的請求,連接建立以后,客戶端和服務器端就可以通過 TCP 連接直接交換數據。
當你獲取 Web Socket 連接后,你可以通過 send() 方法來向服務器發送數據,並通過 onmessage 事件來接收服務器返回的數據。
以下 API 用於創建 WebSocket 對象。
var Socket = new WebSocket(url, [protocol] );*@

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">

        var ws;
        $().ready(function () {
            $('#conn').click(function () {
                ws = new WebSocket('ws://' + window.location.hostname + ':' + window.location.port + '/Home/Demo');
                $('#tips').text('正在連接');
                ws.onopen = function () {
                    $('#tips').text('已經連接');
                }
                ws.onmessage = function (evt) {
                    $('#tips').text(evt.data);
                }
                ws.onerror = function (evt) {
                    $('#tips').text(JSON.stringify(evt));
                }
                ws.onclose = function () {
                    $('#tips').text('已經關閉');
                }
            });

            $('#close').click(function () {
                ws.close();
            });

            $('#send').click(function () {
                if (ws.readyState == WebSocket.OPEN) {
                    ws.send($('#content').val());
                }
                else {
                    $('#tips').text('連接已經關閉');
                }
            });

        });
    </script>
<br/>


<div class="row">

    <form id="form1" runat="server">
        <div>

            <input id="conn" type="button" value="連接" />
            <input id="close" type="button" value="關閉" />
            <span id="tips"></span>
            <input id="content" type="text" />
            <input id="send" type="button" value="發送" />
        </div>
    </form>

   
</div>

2、后端代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.WebSockets;

namespace H5WebSocket.Controllers
{
    public class HomeController : Controller
    {
        WebSocket socket = null;
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public void Demo() {
            //return "Hello World";
            HttpContextBase content = this.HttpContext;
            content.AcceptWebSocketRequest(ProcessChat);
            //return "I am a beautiful girl";
        }



        public String onMessage(String message)
        {
            while (true)
            {
                var buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }

        private async Task ProcessChat(AspNetWebSocketContext context)
        {
            //HttpContextBase  content = this.HttpContext;
            socket = context.WebSocket;
            while (true)
            {
                if (socket.State == WebSocketState.Open)
                {
                    ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[2048]);
                    WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                    

                    while (true) {
                        Thread.Sleep(100);
                        string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
                        userMsg = "你發送了:" + DateTime.Now.ToLongTimeString() + "" + DateTime.Now.ToLongTimeString();
                        buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMsg));
                        await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                    }
                    
                }
                else
                {
                    break;
                }
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM