Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use less cpu #93

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 32 additions & 5 deletions src/Alchemy/TCPServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ public abstract class TcpServer : IDisposable
private TcpListener _listener;

private int _port = 80;
private int _connectrate = 100;


protected TcpServer(int listenPort, IPAddress listenAddress)
{
Expand Down Expand Up @@ -75,6 +77,17 @@ public IPAddress ListenAddress
set { _listenAddress = value; }
}

/// <summary>
/// Sets the maximum rate for new connections per second.
/// </summary>
public int ConnectRateLimit
{
get { return _connectrate; }
set { _connectrate = value; }
}

private int _sleepduration = 0;

/// <summary>
/// Starts this instance.
/// </summary>
Expand All @@ -83,6 +96,10 @@ public virtual void Start()
if (_listener == null)
{
_listener = new TcpListener(_listenAddress, _port);

if (_connectrate > 0)
_sleepduration = 1000 / _connectrate;

ThreadPool.QueueUserWorkItem(Listen, null);
}
}
Expand Down Expand Up @@ -117,15 +134,25 @@ private void Listen(object state)
_listener.Start();
while (_listener != null)
{
try
if (_listener.Pending())
{
_listener.BeginAcceptTcpClient(RunClient, null);
try
{
_listener.BeginAcceptTcpClient(RunClient, null);
}
catch (SocketException)
{
/* Ignore */
}
_connectReady.Wait();
}
catch (SocketException)
else
{
/* Ignore */
if (_sleepduration > 0)
Thread.Sleep(_sleepduration);
}
_connectReady.Wait();


}
}

Expand Down