【问题标题】:Chat application with WebApi/WebSockets backend带有 WebApi/WebSockets 后端的聊天应用程序
【发布时间】: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


    【解决方案1】:

    最好使用SignalR。网上有很多教程。

    【讨论】:

    • SignalR 与客户端实现紧密耦合。如果您只想使用该协议,最好自己动手(尤其是如果您只想发送文本)
    【解决方案2】:

    这是一个使用 WebSockets 的聊天服务器示例:Chat application using Reactive Extennsions

    它使用了另一个 WebSocket 框架,但思路应该差不多。

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 2016-02-15
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-26
      相关资源
      最近更新 更多