Light12306/Web12306/ChatServers.cs
2014-08-13 00:14:00 +08:00

102 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.WebSockets;
namespace Web12306
{
public class ChatServers : IHttpHandler
{
/// <summary>
/// 您将需要在网站的 Web.config 文件中配置此处理程序
/// 并向 IIS 注册它,然后才能使用它。有关详细信息,
/// 请参见下面的链接: http://go.microsoft.com/?linkid=8101007
/// </summary>
#region IHttpHandler Members
public bool IsReusable
{
// 如果无法为其他请求重用托管处理程序,则返回 false。
// 如果按请求保留某些状态信息,则通常这将为 false。
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
{
//if(context.WebSocketNegotiatedProtocol=="Fish12306")
context.AcceptWebSocketRequest(ProcessChat);
}
else
{
context.Response.ContentType = "application/json";
context.Response.WriteFile(context.Server.MapPath("/chatservers.json"));
}
}
#endregion
static readonly HashSet<AspNetWebSocketContext> _allContexts = new HashSet<AspNetWebSocketContext>();
static readonly Dictionary<string, HashSet<AspNetWebSocketContext>> _allRooms = new Dictionary<string, HashSet<AspNetWebSocketContext>>();
private async Task ProcessChat(AspNetWebSocketContext context)
{
WebSocket socket = context.WebSocket;
var roomid = context.Path.Substring(context.Path.LastIndexOf('/'));
lock (_allContexts)
{
if (!_allContexts.Contains(context))
{
_allContexts.Add(context);
var room = _allRooms.ContainsKey(roomid) ? _allRooms[roomid] : null;
if (room == null)
{
room = new HashSet<AspNetWebSocketContext>();
_allRooms.Add(roomid, room);
}
}
}
lock (_allRooms)
{
}
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;
}
}
lock (_allContexts)
{
if (_allContexts.Contains(context))
_allContexts.Remove(context);
if (_allRooms.ContainsKey(roomid))
{
var roomlist = _allRooms[roomid];
roomlist.Remove(context);
}
}
}
}
}