kerryjiang / SuperSocket

SuperSocket is a light weight, cross platform and extensible socket server application framework.
Apache License 2.0
3.93k stars 1.15k forks source link

Attempting to get this working for the first time, instant disconnect, using SuperSocket.WebSocket.WebSocketServer #269

Closed karezza closed 4 years ago

karezza commented 4 years ago

After viewing: https://www.youtube.com/watch?v=JbXurSfeceY Implemented the technique there (see its comment for the code) but using SuperSocket .WebSocket instead of SuperWebSocket.

Added to a pre-existing REST API using C# .net core 2.1, by adding to the Program.cs file.

I can see with my debug messages the server is starting & I am able to telnet to the port from a different computer.

I tried testing using websocket.org/echo.html from another pc. I can see via wireshark a response "HTTP/1.1 101 Switching Protocols", however ... via the testing website it only says DISCONNECT & I'm unable to test sending a message. I'm not getting any exceptions.

Packages installed via nuget with Visual Studio 2019. SuperSocket.WebSocket (1.6.6.1) SuperSocket.Engine (1.6.6.1)

1) Is there another package I need to install? 2) Does this work with .net core? 3) Is there an easy way to see if the websocketserver is functioning as expected? 4) How to increase debugging messages from SuperSocket?

karezza commented 4 years ago

Created a new console app using c#, .net core 2.1, & WebSocketServer (installed via nuget). Same result, able to connect but then there is an immediate disconnect. Also tried 2.2, 3.0, & 3.1.

It never displays "NewSessionConnected".

using SuperWebSocket;
using System;

namespace ConsoleApp1
{
    class Program
    {
        private static WebSocketServer wsServer;
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            wsServer = new WebSocketServer();
            int port = 8088;
            wsServer.Setup(port);
            wsServer.NewSessionConnected += WsServer_NewSessionConnected;
            wsServer.NewMessageReceived += WsServer_NewMessageReceived;
            wsServer.NewDataReceived += WsServer_NewDataReceived;
            wsServer.SessionClosed += WsServer_SessionClosed;
            wsServer.Start();
            Console.WriteLine("Server is running on port " + port + ". Press ENTER to exit....");
            Console.ReadKey();
        }

        private static void WsServer_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
        {
            Console.WriteLine("SessionClosed");
        }

        private static void WsServer_NewDataReceived(WebSocketSession session, byte[] value)
        {
            Console.WriteLine("NewDataReceived");
        }

        private static void WsServer_NewMessageReceived(WebSocketSession session, string value)
        {
            Console.WriteLine("NewMessageReceived: " + value);
            if (value == "Hello server")
            {
                session.Send("Hello client");
            }
        }

        private static void WsServer_NewSessionConnected(WebSocketSession session)
        {
            Console.WriteLine("NewSessionConnected");
        }
    }
}
karezza commented 4 years ago

If I need to be using SuperSocket 2.0 in order to have it work with .net core, could you direct me to some documentation with an example? I cloned the repository & built the code, yet to use it appears to be quite different from the previous method. Looks like I need to be using WebSocketHostBuilder maybe?

karezza commented 4 years ago

Got this to compile, but obviously I don't know how this is supposed to work. Could I get an assist?

static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            //var host = SuperSocketHostBuilder.Create<TextPackageInfo, LinePipelineFilter>()
            var wsServer = SuperSocket.WebSocket.Server.WebSocketHostBuilder.Create()
               .ConfigurePackageHandler(async (s, p) =>
               {
                   await s.SendAsync(Encoding.UTF8.GetBytes(p.Message + "\r\n"));
               })
               .UseSuperSocketWebSocket()
               .ConfigureLogging((hostCtx, loggingBuilder) =>
               {
                   loggingBuilder.AddConsole();
               })
               .ConfigureSuperSocket(options =>
               {
                   options.Name = "Echo Server code modified to be a WebSocket server";
                   options.Listeners = new[] {
                        new ListenOptions
                        {
                            Ip = "Any",
                            Port = 8088
                        }
                   };
               }).Build();

            await wsServer.RunAsync();
}
karezza commented 4 years ago

The code above results in the following:

Hello World!
fail: TcpChannelCreator[0]
      The listener failed to start.
System.Net.Sockets.SocketException (10048): Only one usage of each socket address (protocol/network address/port) is normally permitted.
   at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at SuperSocket.Server.TcpChannelCreator.Start() in C:\Users\travis\source\repos\SuperSocket\src\SuperSocket.Server\TcpChannelCreator.cs:line 71
fail: SuperSocketService[0]
      Failed to listen Ip=Any, Port=8088, Security=None, Path=, BackLog=0, NoDelay=False.
fail: SuperSocketService[0]
      Failed to listen Ip=Any, Port=8088, Security=None, Path=, BackLog=0, NoDelay=False.
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
kerryjiang commented 4 years ago

Probably the previous process hasn't exit yet. To test the server, you better write your test web pages to connect that websocket server or just write some test cases.

karezza commented 4 years ago

I don't see a previous process to shutdown. Tried running again with a new port that I've never tried before 8090 (in this case) and the result was the same. Is that a sufficient test to eliminate the problem as possibly being a previous process still running?

kerryjiang commented 4 years ago

Just check your process list, probably the port has been taken by another application.

karezza commented 4 years ago

I did a reboot and chose another new port that I've never used before, result is the same. I'll try creating a new project with the same code.

kerryjiang commented 4 years ago

Could you run the test cases at first?

Get Outlook for iOShttps://aka.ms/o0ukef


From: karezza notifications@github.com Sent: Sunday, December 22, 2019 8:57:07 PM To: kerryjiang/SuperSocket SuperSocket@noreply.github.com Cc: Kerry Jiang kerry-jiang@hotmail.com; Comment comment@noreply.github.com Subject: Re: [kerryjiang/SuperSocket] Attempting to get this working for the first time, instant disconnect, using SuperSocket.WebSocket.WebSocketServer (#269)

I did a reboot and chose another new port that I've never used before, result is the same. I'll try creating a new project with the same code.

— You are receiving this because you commented. Reply to this email directly, view it on GitHubhttps://eur01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.com%2Fkerryjiang%2FSuperSocket%2Fissues%2F269%3Femail_source%3Dnotifications%26email_token%3DAADPK7FJDLDARFMMRMA5O3TQ2BAKHA5CNFSM4J45INT2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEHQGQ5A%23issuecomment-568354932&data=02%7C01%7C%7Ce11bf9b8fcd646bfe37c08d7876490c8%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637126738300762815&sdata=NTeg%2BannucfCNcXZnB5IE0z5AyMTyLqi718Zx1vMl0U%3D&reserved=0, or unsubscribehttps://eur01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.com%2Fnotifications%2Funsubscribe-auth%2FAADPK7CIJALP5PODS4D3ILDQ2BAKHANCNFSM4J45INTQ&data=02%7C01%7C%7Ce11bf9b8fcd646bfe37c08d7876490c8%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637126738300772826&sdata=XO54imsfBwh0m70oxL6Q2lTZ6wr2oSbCUmtcbIsV9Lk%3D&reserved=0.

karezza commented 4 years ago

Seeing the same result. Here is the process I used to create the project and test:

  1. Using VisualStudio2019, Create new C# .net core project (uses .net core 3.1 by default)
  2. Add all assemblies, under SuperSocket.WebSocket.Server/bin/Debug/netstandard2.1
  3. Install via NuGet: Microsoft.Extensions.Hosting Microsoft.Extensions.Logging
  4. Add using statements: using SuperSocket; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.Threading.Tasks; using System.Text;
  5. Using the following code:

        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");
    
            //var host = SuperSocketHostBuilder.Create<TextPackageInfo, LinePipelineFilter>()
            var wsServer = SuperSocket.WebSocket.Server.WebSocketHostBuilder.Create()
               .ConfigurePackageHandler(async (s, p) =>
               {
                   await s.SendAsync(Encoding.UTF8.GetBytes(p.Message + "\r\n"));
               })
               .UseSuperSocketWebSocket()
               .ConfigureLogging((hostCtx, loggingBuilder) =>
               {
                   loggingBuilder.AddConsole();
               })
               .ConfigureSuperSocket(options =>
               {
                   options.Name = "Echo Server";
                   options.Listeners = new[] {
                        new ListenOptions
                        {
                            Ip = "Any",
                            Port = 9000
                        }
                   };
               }).Build();
    
            await wsServer.RunAsync();
    
        }
karezza commented 4 years ago

When I run a test case to connect to the websocket I see the following exceptions appear: Exception thrown: 'System.IO.FileNotFoundException' in SuperSocket.Channel.dll Exception thrown: 'System.IO.FileNotFoundException' in System.Private.CoreLib.dll Exception thrown: 'System.NullReferenceException' in SuperSocket.Server.dll

Also, the exceptions appear if I simply open a tcp socket connect to the server & port.

The exceptions only appear one time. Have to shut down the server and run again, then test again for them to be seen again.

karezza commented 4 years ago

I added an output at the start of SuperSocket.Server.TcpChannelCreator.Start & when I run my program I can see that the method is being called twice ... though I don't know why. This is probably what is causing the 'listener failed to start' error.

Being that I can connect to the ip/port and see new socket exceptions appear in the running program, this would indicate there is a port listening... though it doesn't function as expected.

kerryjiang commented 4 years ago

Could you just go to the tests/Test in the source code with Visual Studio Code and then run the command “dotnet test” in the terminal tab.

Get Outlook for iOShttps://aka.ms/o0ukef


From: karezza notifications@github.com Sent: Sunday, December 22, 2019 10:14:12 PM To: kerryjiang/SuperSocket SuperSocket@noreply.github.com Cc: Kerry Jiang kerry-jiang@hotmail.com; Comment comment@noreply.github.com Subject: Re: [kerryjiang/SuperSocket] Attempting to get this working for the first time, instant disconnect, using SuperSocket.WebSocket.WebSocketServer (#269)

I added an output at the start of SuperSocket.Server.TcpChannelCreator.Start & when I run my program I can see that the method is being called twice ... though I don't know why. This is probably what is causing the 'listener failed to start' error.

Being that I can connect to the ip/port and see new socket exceptions appear in the running program, this would indicate there is a port listening... though it doesn't function as expected.

— You are receiving this because you commented. Reply to this email directly, view it on GitHubhttps://nam11.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.com%2Fkerryjiang%2FSuperSocket%2Fissues%2F269%3Femail_source%3Dnotifications%26email_token%3DAADPK7FJZL5KUG7UWJ5N4EDQ2BJLJA5CNFSM4J45INT2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEHQKDNA%23issuecomment-568369588&data=02%7C01%7C%7C3ef5ea41ebdb4e226a4f08d7876f547a%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637126784528899964&sdata=dTo%2F94NpfQL8rLJjJs2BGpqsastF22uTiSTXxKVLReM%3D&reserved=0, or unsubscribehttps://nam11.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.com%2Fnotifications%2Funsubscribe-auth%2FAADPK7HXH6QYMYGJ2XMDLZ3Q2BJLJANCNFSM4J45INTQ&data=02%7C01%7C%7C3ef5ea41ebdb4e226a4f08d7876f547a%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637126784528909973&sdata=Q%2B0DapDwGBIRPf4iyUaeAOV2yserNJgrNF%2FvnV%2FG2DY%3D&reserved=0.

karezza commented 4 years ago

I right-clicked on Test & selected "Run Tests". 45 tests ran and Passed.

From the command window and the test/test directory, running "dotnet test" ran 45 tests and all passed.

kerryjiang commented 4 years ago

OK, just follow the usages in the unit tests.

karezza commented 4 years ago

I'll take a look and report back.

jzabroski commented 4 years ago

The advice to use a web browser to test a web socket server seems bad/klunky. Perhaps something like websocket-mock could be helpful: https://github.com/davidkiss/websocket-mock

jzabroski commented 4 years ago

Or maybe just: https://docs.microsoft.com/en-us/dotnet/api/system.net.websockets.clientwebsocket?view=netframework-4.8

karezza commented 4 years ago

Will keep an eye out for documentation.

karezza commented 4 years ago

Not sure what to do. Closing as the library has not been released yet so there is no expectation that it should be usable yet.