sta / websocket-sharp

A C# implementation of the WebSocket protocol client and server
http://sta.github.io/websocket-sharp
MIT License
5.72k stars 1.66k forks source link

How do WebSocketBehaviors work with a WebSocketServer? #742

Open jheliker opened 10 months ago

jheliker commented 10 months ago

Hello @sta -

Thanks for the great library! I'm having trouble understanding how WebSocketBehaviors work for a WebSocketServer.

Is there a new instance of the WebSocketBehavior instantiated for every new connection made to the server?

I'm trying to use a WebSocketBehavior to manage all connected clients and I'm getting duplicated messaging.

GholibjonMadiyarov commented 10 months ago

`protected override void OnStart(string[] args) { try { server = new WebSocketServer("IPPort");

    server.AddWebSocketService<Web>("/Web");
    //server.AddWebSocketService<Phone>("/Phone");
    //server.AddWebSocketService<Tablet>("/Tablet");
    //server.AddWebSocketService<Desktop>("/Desktop");

    server.Start();
    Logs.toFile("OnStartLog.txt", "Success");
}
catch (Exception error)
{
    Logs.toFile("OnStartLog.txt", " Exception: " + error.Message);
}

}`

GholibjonMadiyarov commented 10 months ago

`class Web : WebSocketBehavior { public Web() {

}

protected override void OnOpen()
{
    Logs.toFile("ClientOpenLog.txt", "Id: " + ID);
}

protected override void OnMessage(MessageEventArgs e)
{
    try
    {
        JObject data = JObject.Parse(e.Data);
        switch (data["query"].ToString())
        {
            case "query1":
                //
                break;

            case "query2":
                //
                break;

            default:
                Logs.toFile("OnMessageLog.txt", " Undifined Query:" + data["query"]);
                break;
        }
    }
    catch (Exception exception)
    {
        Logs.toFile("MessageRecievedLog.txt", "Exception:" + exception.Message);
    }
}

protected override void OnError(ErrorEventArgs e)
{
    Logs.toFile("SocketExceptionsLog.txt", "SocketException:" + e.Message);
}

protected override void OnClose(CloseEventArgs e)
{
    Logs.toFile("ClientCloseLog.txt", "Id: " + ID + ", Code: " + e.Code + ", Reason:" + e.Reason + ", WasClean:" + e.WasClean);
}

}`