Skip to content

Instantly share code, notes, and snippets.

@ctigeek
Created June 22, 2020 21:49
Show Gist options
  • Save ctigeek/fd7e2b50b11bc4254440ada85dbd0d65 to your computer and use it in GitHub Desktop.
Save ctigeek/fd7e2b50b11bc4254440ada85dbd0d65 to your computer and use it in GitHub Desktop.
A simple TCP listener. Assumes you're sending UTF8 text to it.
using System;
using System.IO;
using System.Net;
using System.Text;
namespace TcpListener
{
class Program
{
static void Main(string[] args)
{
byte[] receiveBuffer = new byte[65536];
var listener = new System.Net.Sockets.TcpListener(IPAddress.Any, 5151);
listener.Start();
Console.WriteLine("Started.........");
while (true)
{
using (var tcpClient = listener.AcceptTcpClient())
{
Console.WriteLine("got a connection...");
using (var stream = tcpClient.GetStream())
{
while (tcpClient.Connected)
{
try
{
var bytes = stream.Read(receiveBuffer, 0, tcpClient.ReceiveBufferSize);
if (bytes == 0) break;
Console.WriteLine(Encoding.UTF8.GetString(receiveBuffer, 0, bytes));
}
catch (IOException)
{
break;
}
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment