Created
January 18, 2024 21:22
-
-
Save fkasler/be0b23368dc56b997ede3364aa477a62 to your computer and use it in GitHub Desktop.
Reuse Addr
This file contains 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
# Load assembly | |
Add-Type -TypeDefinition @" | |
using System; | |
using System.Net; | |
using System.Net.Sockets; | |
public class TcpServer { | |
private TcpListener _listener; | |
public TcpServer() | |
{ | |
this._listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 5001); | |
this._listener.Start(); | |
// Set SocketOption to allow address reuse | |
this._listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); | |
} | |
public void Run() | |
{ | |
while(true) | |
{ | |
Socket client = this._listener.AcceptSocket(); | |
if(client.Connected) | |
{ | |
Console.WriteLine("Client connected..."); | |
// Do something with the client | |
client.Close(); // Ensure to close the client | |
} | |
} | |
} | |
} | |
"@ -ReferencedAssemblies System.Net | |
# Now, instantiate and run the server | |
$server = New-Object -TypeName TcpServer | |
$server.Run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment