统一后台代码:
LogHelper.LogHelper _log = new LogHelper.LogHelper();
public void ProcessRequest(HttpContext context)
{
//处理WebSocket 请求
context.AcceptWebSocketRequest(DoWork);
}
/// <summary>
/// 委托处理函数定义
/// </summary>
/// <param name="context">当前WebSocket上下文</param>
/// <returns></returns>
public async Task DoWork(AspNetWebSocketContext context)
{
//1.获取当前WebSocket 对象
WebSocket socket = context.WebSocket;
//2.监视相应
while (true)
{
/*
* 此处缓存数组指定读取客户端数据的长度
* 如果客户端发送数据超过当前缓存区,则会读取多次
*/
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[10]);
//接收客户端信息
CancellationToken token;
WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, token);
if (socket.State == WebSocketState.Open)
{
//1.获取用户提交内容
string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, buffer.Array.Length);
//2.将内容以字符串的方式,返回客户端
string echo = "您传入的内容为:" + userMsg + ",数据总量:" + result.Count + ",数据类型" + result.MessageType;
buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(echo));
await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
else { break; }
}
}
1.发送二进制数组
<input type="button" value="发送" id="sendBtn" οnclick="sendClick();" />
<input type="button" value="关闭" id="closeBtn" οnclick="closeClick();" />
<div id="result"></div>
JS:
var url = 'ws://localhost:55373/ashx/upload2.ashx';
var ws = null;
ws = new WebSocket(url);
ws.onopen = function (e) {
console.log('链接打开');
}
ws.onmessage = function (e) {
showData(e.data);
}
ws.onclose = function (e) {
console.info(e);
console.log('链接已经关闭');
}
ws.onerror = function (e) {
console.log('发生异常:' + e.message);
}
//显示后台字节数组
function showData(data) {
var result = document.getElementById('result');
result.innerHTML += data + '<br />';
}
//发送
function sendClick() {
var content = new Int8Array([65, 66, 67, 68]);
//如果发送缓冲区没有数据才继续发送
if (ws.bufferedAmount <= 0) {
ws.send(content);
}
}
//关闭
function closeClick() {
ws.close();
ws = null;
}
2.发送字符串
<input type="button" value="打开链接" οnclick="openClick();" />
<input type="text" id="txt1" />
<input type="button" value="发送" id="sendBtn" οnclick="sendClick();" />
<input type="button" value="关闭" id="closeBtn" οnclick="closeClick();" />
<div id="result"></div>
JS:
var url = 'ws://localhost:55373/ashx/upload2.ashx';
var ws = null;
//打开链接
function openClick() {
ws = new WebSocket(url);
ws.onopen = function (e) {
console.log('链接打开');
}
ws.onmessage = function (e) {
showData(e.data);
}
ws.onclose = function (e) {
console.info(e);
console.log('链接已经关闭');
}
ws.onerror = function (e) {
console.log('发生异常:' + e.message);
}
}
//显示后台传送结果
function showData(data) {
var result = document.getElementById('result');
result.innerHTML += data + '<br />';
}
//发送
function sendClick() {
var content = document.getElementById('txt1').value;
//如果发送缓冲区没有数据才继续发送
if (ws.bufferedAmount <= 0) {
ws.send(content);
}
}
//关闭
function closeClick() {
ws.close();
ws = null;
}
显示说明:如果后台读取缓冲区,小于发送内容,后台则分多次读取
实例一: http://blog.csdn.net/u011127019/article/details/52457551