Created
January 29, 2018 17:33
-
-
Save rdeioris/7323f7ba5cb290d2696fb2b20dcf5695 to your computer and use it in GitHub Desktop.
Non blocking Poll based (slow) server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| using System.Net; | |
| using System.Net.Sockets; | |
| using System.IO; | |
| namespace HttpConcurrentServer | |
| { | |
| class Server | |
| { | |
| List<Socket> serverSockets; | |
| List<Socket> clientSockets; | |
| public Server(int port) | |
| { | |
| Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); | |
| server.Blocking = false; | |
| IPEndPoint serverAddress = new IPEndPoint(IPAddress.Any, port); | |
| server.Bind(serverAddress); | |
| server.Listen(10); | |
| serverSockets = new List<Socket>(); | |
| serverSockets.Add(server); | |
| clientSockets = new List<Socket>(); | |
| } | |
| public void Run() | |
| { | |
| byte[] data = new byte[8192]; | |
| while (true) | |
| { | |
| // iterate server sockets, checking for item in the backlog | |
| foreach (Socket socket in serverSockets) | |
| { | |
| if (socket.Poll(0, SelectMode.SelectRead)) | |
| { | |
| Socket newClient = socket.Accept(); | |
| Console.WriteLine("new client available"); | |
| // limit clients number | |
| if (clientSockets.Count > 10) | |
| { | |
| newClient.Close(); | |
| continue; | |
| } | |
| clientSockets.Add(newClient); | |
| } | |
| } | |
| List<Socket> deadClients = new List<Socket>(); | |
| // now iterate clients | |
| foreach (Socket socket in clientSockets) | |
| { | |
| if (socket.Poll(0, SelectMode.SelectRead)) | |
| { | |
| int dataLength = socket.Receive(data); | |
| if (dataLength <= 0) | |
| { | |
| socket.Close(); | |
| deadClients.Add(socket); | |
| continue; | |
| } | |
| string httpData = Encoding.ASCII.GetString(data, 0, dataLength); | |
| Console.WriteLine(httpData); | |
| } | |
| } | |
| // remove dead clients | |
| foreach (Socket socket in deadClients) | |
| { | |
| clientSockets.Remove(socket); | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment