Hosting other Http Listener with Super WebSockets in Console Application.

Feb 22, 2013 at 9:55 PM
Hi kerryjiang,

I need to support long polling for older browsers along with Super Websockets for the websocket enabled browsers. I am using Microsoft.Owin.Hosting.WebApplication framework with SignalR to create the Http Listener for the older browsers, The Signalr Http Listener works fine in console Application when Isolated and Super Websockets is not running, but it does not work when I start the Super Websockets server in the same application, Super Websockets runs fine but the SignalR Http listener fails to run on the specified port. Do you think I am having Http Listeners conflict and Super Websockets is interfering with SignalR.


class Host
{
    static void Main(string[] args)
    {

        log4net.Config.XmlConfigurator.Configure();

        StartSignalR();
        StartSuperWebSockets();

        Console.ReadLine();
    }

    private static void StartSuperWebSockets()
    {
        WebSocketFacade.StartSocket();
        Console.WriteLine("Websocket server has been started");
        Logger.LogInfo("Super WebSockets Server has been Started");

    }

    private static void StartSignalR()
    {
        string url = "http://localhost:9999/";

        using (WebApplication.Start<Startup>(url))
        {
            Logger.LogInfo("Server has started running on " + url);
            Console.WriteLine("Server running on {0}", url);
        }
    }
}


class WebSocketFacade
{
    private static List<WebSocketSession> m_Sessions = new List<WebSocketSession>();
    private static List<WebSocketSession> m_SecureSessions = new List<WebSocketSession>();
    private static object m_SessionSyncRoot = new object();
    private static object m_SecureSessionSyncRoot = new object();
    private static Timer m_SecureSocketPushTimer;
    private static int m_Index = 0;

    public static void SendEvent(string message)
    {
        foreach (WebSocketSession session in m_Sessions)
        {
            session.SendResponseAsync(message);
        }
    }


    public static void StartSocket()
    {
        LogUtil.Setup();
        StartSuperWebSocketByConfig();
        //StartSuperWebSocketByProgramming();
        var ts = new TimeSpan(0, 0, 0, 0, 5000);
        m_SecureSocketPushTimer = new Timer(OnSecureSocketPushTimerCallback, new object(), ts, ts);
    }

    public static void EndSocket()
    {
        //  Code that runs on application shutdown
        m_SecureSocketPushTimer.Change(Timeout.Infinite, Timeout.Infinite);
        m_SecureSocketPushTimer.Dispose();
        SocketServerManager.Stop();
    }

    static void StartSuperWebSocketByConfig()
    {
        var serverConfig = ConfigurationManager.GetSection("socketServer") as SocketServiceConfig;
        if (!SocketServerManager.Initialize(serverConfig))
            return;

        var socketServer = SocketServerManager.GetServerByName("SuperWebSocket") as WebSocketServer;
        var secureSocketServer = SocketServerManager.GetServerByName("SecureSuperWebSocket") as WebSocketServer;


        // Application["SecureWebSocketPort"] = secureSocketServer.Config.Port;

        socketServer.NewMessageReceived += new SessionEventHandler<WebSocketSession, string>(socketServer_NewMessageReceived);
        socketServer.NewSessionConnected += new SessionEventHandler<WebSocketSession>(socketServer_NewSessionConnected);
        socketServer.SessionClosed += new SessionEventHandler<WebSocketSession, CloseReason>(socketServer_SessionClosed);

        //  secureSocketServer.NewSessionConnected += new SessionEventHandler<WebSocketSession>(secureSocketServer_NewSessionConnected);
        //  secureSocketServer.SessionClosed += new SessionEventHandler<WebSocketSession, CloseReason>(secureSocketServer_SessionClosed);

        if (!SocketServerManager.Start())
            SocketServerManager.Stop();
    }

    static void socketServer_NewMessageReceived(WebSocketSession session, string e)
    {
        // SendToAll(session.Cookies["name"] + ": " + e);
        string[] data = e.Split(new char[] { ',' });

        Logger.LogInfo("Browser has sent this information to the server." + e);

        Task.Factory.StartNew(() => SendToClientWithDelay("Data from machine with MacId '" + data[0] + "' and computer Name '" + data[1] + "' has been processed", session.IdentityKey));
        SendToClient("Data received and processing", session.IdentityKey);


    }


    static void socketServer_NewSessionConnected(WebSocketSession session)
    {
        lock (m_SessionSyncRoot)
            m_Sessions.Add(session);

        // SendToAll("System: " + session.Cookies["name"] + " connected");
        SendToClient("System: " + " connected", session.IdentityKey);

        Logger.LogInfo("Browser has established a connection  with the Server");

        System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        Task.Factory.StartNew(() => SendToClientWithDelay(oSerializer.Serialize(new { HalMessage = "true", MacId = HalUtility.MacId, ComputerName = HalUtility.ComputerName }), session.IdentityKey));
        Task.Factory.StartNew(() => SendToClientWithDelay(String.Format("Mac Address: '{0}' and Computer Name: '{1}'", HalUtility.MacId, HalUtility.ComputerName), session.IdentityKey));
    }

    static void socketServer_SessionClosed(WebSocketSession session, CloseReason reason)
    {
        lock (m_SessionSyncRoot)
            m_Sessions.Remove(session);

        if (reason == CloseReason.ServerShutdown)
            return;

        // SendToAll("System: " + " disconnected");
    }

    static void SendToAll(string message)
    {
        lock (m_SessionSyncRoot)
        {
            foreach (var s in m_Sessions)
            {
                //s.SendResponse(message);
                s.SendResponseAsync(message);
            }
        }
    }

    static void SendToClient(string message, string identifier)
    {
        lock (m_SessionSyncRoot)
        {
            foreach (var s in m_Sessions)
            {
                //s.SendResponse(message);
                if (s.IdentityKey == identifier)
                {
                    s.SendResponseAsync(message);
                }
            }
        }
    }

    static void SendToClientWithDelay(string message, string identifier)
    {
        System.Threading.Thread.Sleep(7000);
        Logger.LogInfo("Server is pushing the following information to the Browser: " + message);
        SendToClient(message, identifier);

    }

    static void OnSecureSocketPushTimerCallback(object state)
    {
        lock (m_SecureSessionSyncRoot)
        {
            m_SecureSessions.ForEach(s => s.SendResponseAsync("Push data from WebSocket. [" + (m_Index++) + "] Current Time: " + DateTime.Now));
        }
    }
}
}
Coordinator
Feb 23, 2013 at 4:01 AM
Sorry, SuperSocket/SuperWebSocket cannot support share port with other application.