Skip to content

Commit

Permalink
perf: caching remoteAddress
Browse files Browse the repository at this point in the history
  • Loading branch information
James-Frowen committed Jun 8, 2023
1 parent 92af868 commit d2f63ba
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 9 deletions.
25 changes: 25 additions & 0 deletions source/Runtime/Common/Connection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ internal sealed class Connection : IDisposable
/// <para>Only valid on server</para>
/// </summary>
public Request request;
/// <summary>
/// RemoteEndpoint address or address from request header
/// <para>Only valid on server</para>
/// </summary>
public string remoteAddress;

public Stream stream;
public Thread receiveThread;
Expand Down Expand Up @@ -100,5 +105,25 @@ public override string ToString()
return $"[Conn:{connId}, endPoint:n/a]";
}
}

/// <summary>
/// Gets the address based on the <see cref="request"/> and RemoteEndPoint
/// <para>Called after ServerHandShake is accepted</para>
/// </summary>
/// <exception cref="NotImplementedException"></exception>
internal string CalculateAddress()
{
var headers = request.Headers;
if (headers.TryGetValue("X-Forwarded-For", out var forwardFor))
{
var ips = forwardFor.ToString().Split(',');
var actualClientIP = ips[0];
// Remove the port number from the address
string addressWithoutPort = remoteAddress.Split(':')[0];
return addressWithoutPort;
}

return client.Client.RemoteEndPoint.ToString();
}
}
}
1 change: 1 addition & 0 deletions source/Runtime/Server/ServerHandshake.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ public bool TryHandshake(Connection conn)
AcceptHandshake(stream, msg);

conn.request = new Request(msg);
conn.remoteAddress = conn.CalculateAddress();

return true;
}
Expand Down
10 changes: 1 addition & 9 deletions source/Runtime/Server/WebSocketServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -217,15 +217,7 @@ public string GetClientAddress(int id)
return null;
}

var headers = conn.request.Headers;
if (headers.TryGetValue("X-Forwarded-For", out var forwardFor))
{
var ips = forwardFor.ToString().Split(',');
var actualClientIP = ips[0];
return actualClientIP;
}

return conn.client.Client.RemoteEndPoint.ToString();
return conn.remoteAddress;
}

public Request GetClientRequest(int id)
Expand Down

0 comments on commit d2f63ba

Please sign in to comment.