zoukankan      html  css  js  c++  java
  • websocket在.net4.5中实现的简单demo

    以下代码环境要求:win8或win10, .net4.5+IIS8

    win7上是IIS7,win7上.net本身不直接支持websocket, win7可以用superwebsocket, 或自己根据协议用TCPListener实现

    handler代码:

    using System;
    using System.Net.WebSockets;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.WebSockets;
    
    namespace websocket
    {
        /// <summary>
        /// Handler1 的摘要说明
        /// </summary>
        public class Handler1 : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                if (context.IsWebSocketRequest)
                {
                    context.AcceptWebSocketRequest(ProcessChat);
                } 
            }
    
            private async Task ProcessChat(AspNetWebSocketContext context)
            {
                WebSocket 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);
                        string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
                        userMsg = "你发送了:" + userMsg + "" + DateTime.Now.ToLongTimeString();
                        buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMsg));
                        await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                    }
                    else
                    {
                        break;
                    }
                }
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }

    前台代码:

    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
        <script src="jquery-2.0.3.min.js"></script>
        <script>
            var ws;
            $().ready(function ()
            {
                $('#conn').click(function ()
                {
                    ws = new WebSocket('ws://' + window.location.hostname+':'+window.location.port + '/Handler1.ashx');
                    $('#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>
    </head>
    <body>
        <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>
    </body>

    web.config:

      <system.web>
        <httpRuntime targetFramework="4.5"/>
      </system.web>
  • 相关阅读:
    Java web过滤器验证登录(避免未经登录进入主页)
    基于struts2+hibernate+spring(ssh2)的登录验证码的实现
    Linux下载工具wget详解
    Linux下python升级步骤
    程序猿的一些幽默(正中啊)
    查看Linux版本系统信息方法汇总
    VS下如何配置才能使用 cl 命令行方式编译 C/C++ 程序
    Linux下ln链接命令详解
    JBPM handler
    Linux下有趣的命令
  • 原文地址:https://www.cnblogs.com/langu/p/3485676.html
Copyright © 2011-2022 走看看