Created
April 22, 2019 09:55
-
-
Save irwinwilliams/575a1fe6481ab09af8d21f11ffb89835 to your computer and use it in GitHub Desktop.
Simple listener to confirm a networking question I had on StackOverflow
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
using System; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Threading.Tasks; | |
namespace ListenOnAny | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var address = args.Length == 0 ? IPAddress.Loopback: IPAddress.Any; | |
var port = 20000; | |
var listener = new TcpListener(address, port); | |
listener.Start(); | |
bool listening = true; | |
var listenAction= new Action(() => | |
{ | |
while (listening) | |
{ | |
var socket = listener.AcceptSocket(); | |
var remoteAddr = socket.RemoteEndPoint.ToString(); | |
Console.WriteLine($"Got connected from {remoteAddr}. Closing now."); | |
socket.Close(); | |
} | |
}); | |
var listenTask = new Task(listenAction); | |
listenTask.Start(); | |
Console.WriteLine($"Listening on {port}. Press a key to end this"); | |
Console.Read(); | |
listening = false; | |
listener.Stop(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment