【发布时间】:2015-07-30 13:53:10
【问题描述】:
我正在尝试使用 iOS 和 Android 客户端编写一个简单的聊天应用程序。我正在按照http://blogs.msdn.com/b/youssefm/archive/2012/07/17/building-real-time-web-apps-with-asp-net-webapi-and-websockets.aspx 此处的教程使用 WebSockets。但是,我需要能够向单个“聊天室”发送消息,而不是向所有用户广播(实际上只有 2 个用户,我和我正在聊天的人)。目前我正在这样做:
using Microsoft.Web.WebSockets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace ChatPractice.Controllers
{
public class ChatController : ApiController
{
public HttpResponseMessage Get(string username, int roomId)
{
HttpContext.Current.AcceptWebSocketRequest(new ChatWebSocketHandler(username, roomId));
return Request.CreateResponse(HttpStatusCode.SwitchingProtocols);
}
}
class ChatWebSocketHandler : WebSocketHandler
{
private static WebSocketCollection _chatClients = new WebSocketCollection();
private string _username;
private int _roomId;
public ChatWebSocketHandler(string username, int roomId)
{
_username = username;
_roomId = roomId;
}
public override void OnOpen()
{
_chatClients.Add(this);
}
public override void OnMessage(string message)
{
var room = _chatClients.Where(x => ((ChatWebSocketHandler)x)._roomId == _roomId);
message = _username + ": " + message;
foreach (var user in room)
user.Send(message);
//_chatClients.Broadcast(_username + ": " + message);
}
}
}
是使用 linq 来获取正确的房间还是有更好的方法来获取它?
【问题讨论】:
标签: c# asp.net linq asp.net-web-api websocket