GBreen12
GBreen12

Reputation: 1900

Chat application with WebApi/WebSockets backend

I am trying to write a simple chat application with iOS and Android clients. I am following the tutorial here http://blogs.msdn.com/b/youssefm/archive/2012/07/17/building-real-time-web-apps-with-asp-net-webapi-and-websockets.aspx to use WebSockets. However, I need to be able to send messages to a single "Chatroom" rather than broadcast to all the users (in reality there will only ever be 2 users, me and the person I'm chatting with). Currently I am doing this:

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);
        }
    }
}

Is using linq to get the correct room here correct or is there a better way to get to it?

Upvotes: 0

Views: 8250

Answers (2)

vtortola
vtortola

Reputation: 35945

This is an example of a chat server using WebSockets: Chat application using Reactive Extennsions.

It uses another WebSocket framework, but the idea should be pretty much the same.

Upvotes: 1

jomargon
jomargon

Reputation: 169

It's better to use SignalR. There's a lot of tutorials online.

Upvotes: 0

Related Questions