WebSocket在Asp.Net中的例子
环境
以下代码环境要求:win8或win10, .net4.5+IIS8
部署到IIS8上面 转到 Windows程序和功能 -打开Windows功能里面 IIS选项启动4.5 和WebSocket支持 否则会报错误的。
win7上是IIS7,win7上.net本身不直接支持websocket, win7可以用superwebsocket, 或自己根据协议用TCPListener实现
我使用VS2013+iis EXPRESS 执行也失败,context.IsWebSocketRequest一直为false,建议用VS2015和系统的IIS 8部署环境,不要用vs环境
Index.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="SimpleWebSocket.WebForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<span id="webSocketStatusSpan"></span>
<br />
<span id="webSocketReceiveDataSpan"></span>
<br />
<span>请输入一个字符串</span>
<br />
<input id="nameTextBox" type="text" value="" />
<input type="button" value="Send data" onclick="SendData();" />
<input type="button" value="Close WebSocket" onclick="CloseWebSocket();" />
</div>
</form><script type="text/javascript">
var webSocketStatusSpan = document.getElementById("webSocketStatusSpan");
var webSocketReceiveDataSpan = document.getElementById("webSocketReceiveDataSpan");
var nameTextBox = document.getElementById("nameTextBox");
var webSocket;
//HTTP处理程序的地址
//var handlerUrl = "ws://localhost:2659/SimpleWebSocket/WebSocketHandler.ashx";
var handlerUrl = "ws://localhost:2659/WebSocketHandler.ashx";
function SendData() {
//初始化WebSocket
InitWebSocket();
//如果WebSocket打开,发送数据
if (webSocket.OPEN && webSocket.readyState == 1)
webSocket.send(nameTextBox.value);
//如果WebSocket关闭,显示消息
if (webSocket.readyState == 2 || webSocket.readyState == 3)
webSocketStatusSpan.innerText = "WebSocket关闭了,无法发送数据";
}
function CloseWebSocket() {
webSocket.close();
}
function InitWebSocket() {
//如果WebSocket对象未初始化,我们将初始化它
if (webSocket == undefined) {
webSocket = new WebSocket(handlerUrl);
//打开连接处理程序
webSocket.onopen = function () {
webSocketStatusSpan.innerText = "WebSocket打开了.";
webSocket.send(nameTextBox.value);
};
//消息数据处理程序
webSocket.onmessage = function (e) {
webSocketReceiveDataSpan.innerText = e.data;
};
//关闭事件处理程序
webSocket.onclose = function () {
webSocketStatusSpan.innerText = "WebSocket closed.";
};
//错误事件处理程序
webSocket.onerror = function (e) {
webSocketStatusSpan.innerText = e.message;
}
}
}
</script>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
WebSocketHandler.ashx代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.WebSockets;
namespace SimpleWebSocket
{
/// <summary>
///
/// </summary>
public class WebSocketHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//检查 查询是否是WebSocket请求
if (HttpContext.Current.IsWebSocketRequest)
{
//如果是,我们附加异步处理程序
context.AcceptWebSocketRequest(WebSocketRequestHandler);
}
}
public bool IsReusable { get { return false; } }
//异步请求处理程序
public async Task WebSocketRequestHandler(AspNetWebSocketContext webSocketContext)
{
//获取当前的WebSocket对象
WebSocket webSocket = webSocketContext.WebSocket;
/*
* 我们定义一个常数,它将表示接收到的数据的大小。 它是由我们建立的,我们可以设定任何值。 我们知道在这种情况下,发送的数据的大小非常小。
*/
const int maxMessageSize = 1024;
//received bits的缓冲区
var receivedDataBuffer = new ArraySegment<Byte>(new Byte[maxMessageSize]);
var cancellationToken = new CancellationToken();
//检查WebSocket状态
while (webSocket.State == WebSocketState.Open)
{
//读取数据
WebSocketReceiveResult webSocketReceiveResult = await webSocket.ReceiveAsync(receivedDataBuffer, cancellationToken);
//如果输入帧为取消帧,发送close命令
if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, cancellationToken);
}
else
{
byte[] payloadData = receivedDataBuffer.Array.Where(b => b != 0).ToArray();
//因为我们知道这是一个字符串,我们转换它
string receiveString = System.Text.Encoding.UTF8.GetString(payloadData, 0, payloadData.Length);
//将字符串转换为字节数组.
var newString = String.Format("Hello, " + receiveString + " ! Time {0}", DateTime.Now.ToString());
Byte[] bytes = System.Text.Encoding.UTF8.GetBytes(newString);
//发回数据
await webSocket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, cancellationToken);
}
}
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75