我正在使用Microsoft webscoket实现ASP.net websocket服务器。我有一个将数据发送到客户端的功能。以下是课程。
public class MyWebSocketHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
{
context.AcceptWebSocketRequest(DoTalking);
}
}
public bool IsReusable
{
get
{
return false;
}
}
public async Task DoTalking(AspNetWebSocketContext context)
{
WebSocket socket = context.WebSocket;
while (true)
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
if (socket.State == WebSocketState.Open)
{
string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
userMessage = "Message from client : " + userMessage;
}
else
{
break;
}
}
}
public async Task SendToClient(AspNetWebSocketContext context)
{
WebSocket socket = context.WebSocket;
//WebSocket socket = context.WebSocket;
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message));
await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
public void callSendToClient()
{
var task = SendToClient(Problem is here!);
task.Wait();
}
private string message { get; set; }
}
}
我的问题是当我调用SendToClient方法时如何获取AspNetWebSocketContext?我被困在这一点上。其实我想从另一个.aspx页面调用SendToClient()方法。需要一些帮助。