Skip to content

Instantly share code, notes, and snippets.

@irwinwilliams
Created April 22, 2019 09:55
Show Gist options
  • Save irwinwilliams/575a1fe6481ab09af8d21f11ffb89835 to your computer and use it in GitHub Desktop.
Save irwinwilliams/575a1fe6481ab09af8d21f11ffb89835 to your computer and use it in GitHub Desktop.
Simple listener to confirm a networking question I had on StackOverflow
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