Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSocket windows service listening on port 8080

I'm new to Windows service development, and need to build one in C# that will listen on port 8080 for data coming in, then parse it. I've found information about System.Net.WebSockets, System.Net.Sockets, and third-party libraries, such as SuperSocket. There's this example, but not sure what goes in the OnStart() and what goes in OnStop() methods of my Windows service class. Another example is here, but that's also not covering Windows service specifically. For basic Windows service development, there's this MSDN article.

I'm thinking this goes in OnStart():

Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
serverSocket.Listen(128);
serverSocket.BeginAccept(null, 0, OnAccept, null);

What would I put into the OnStop()?

The data stream coming in doesn't require any authentication. Would I still need to do a handshake?

Your help is appreciated.

like image 205
Alex Avatar asked Oct 29 '22 17:10

Alex


1 Answers

Since you wish to use port 8080 as listening port, I'm going to assume you are essentially dealing with http traffic. Instead of using raw sockets, you should look into OWIN Self Hosted web server. Alternatively NancyFx can work as well.

OnStop() is called when windows tries to stop the service. You can think of it as your Dispose for service. OnStart() is similarly your function to do initializations. I'd suggest you look into the really nice library TopShelf to start writing Windows Services.

like image 170
Maverik Avatar answered Nov 10 '22 14:11

Maverik