H5WebSocket消息推送

一、效果圖javascript

二、前端代碼前端

@{
    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>

二、後端代碼java

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;
                }
            }
        }
    }
}
相關文章
相關標籤/搜索