websocket在.net4.5中实现的简单demo
生活随笔
收集整理的這篇文章主要介紹了
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>?
轉載于:https://www.cnblogs.com/langu/p/3485676.html
總結
以上是生活随笔為你收集整理的websocket在.net4.5中实现的简单demo的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于visual Studio2013解
- 下一篇: Spark 源码分析 -- RDD