Skip to content

Instantly share code, notes, and snippets.

@fkasler
Created January 18, 2024 21:22
Show Gist options
  • Save fkasler/be0b23368dc56b997ede3364aa477a62 to your computer and use it in GitHub Desktop.
Save fkasler/be0b23368dc56b997ede3364aa477a62 to your computer and use it in GitHub Desktop.
Reuse Addr
# 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