Last active
January 29, 2018 18:51
-
-
Save rdeioris/3833afa9c27c1e5a0eaa7224e54f6a5d to your computer and use it in GitHub Desktop.
Non blocking Select based 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) | |
| { | |
| List<Socket> readingSockets = new List<Socket>(serverSockets); | |
| readingSockets.AddRange(clientSockets); | |
| List<Socket> writingSockets = new List<Socket>(); | |
| List<Socket> errorSockets = new List<Socket>(); | |
| Console.WriteLine(readingSockets.Count); | |
| // Reactor pattern c10k | |
| Socket.Select(readingSockets, writingSockets, errorSockets, -1); | |
| Console.WriteLine(readingSockets.Count); | |
| foreach (Socket readSocket in readingSockets) | |
| { | |
| // is it a server socket? | |
| if (serverSockets.Contains(readSocket)) | |
| { | |
| Socket newClient = readSocket.Accept(); | |
| newClient.Blocking = false; | |
| clientSockets.Add(newClient); | |
| continue; | |
| } | |
| // is it a client socket? | |
| if (clientSockets.Contains(readSocket)) | |
| { | |
| int dataLength = readSocket.Receive(data); | |
| if (dataLength <= 0) | |
| { | |
| readSocket.Close(); | |
| clientSockets.Remove(readSocket); | |
| continue; | |
| } | |
| string httpData = Encoding.ASCII.GetString(data, 0, dataLength); | |
| Console.WriteLine(httpData); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment