[C#] How to create a simple TCP Listener

TheRealMoonman

I eat babies
Sep 30, 2014
360
74
Hello, im going to show you how to create a simple TCP listener in C#, this is a very basic way on how to do it, anyways enjoy :)

DOWNLOADS:
Visual Express:

1. Create a console application
And put this code in
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.IO;

namespace MyLocal
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener listener = new TcpListener(8080);
            listener.Start();

            while (true)
            {
                Console.WriteLine("Waiting for a connection");
                TcpClient client = listener.AcceptTcpClient();
                StreamReader sr = new StreamReader(client.GetStream());
                StreamWriter sw = new StreamWriter(client.GetStream());
                try
                {
                    // Request
                    string request = sr.ReadLine();
                    Console.WriteLine(request);
                    string[] tokens = request.Split(' ');
                    string page = tokens[1];
                    if (page == "/")
                    {
                        page = "/default.htm";
                    }

                    //Find File
                    StreamReader file = new StreamReader("../../web" + page);
                    sw.WriteLine("HTTP/1.0 200 OK\n");

                    //Send File
                    string data = file.ReadLine();
                    while (data != null)
                    {
                        sw.WriteLine(data);
                        sw.Flush();
                        data = file.ReadLine();
                    }
                }
                catch (Exception e)
                {
                    // error
                    sw.WriteLine("HTTP/1.0 404 OK\n");
                    sw.WriteLine("<h1> Sorry, but your file was not found!</h1>");
                    sw.Flush();
                }
                client.Close();
            }
        }
    }
}
NOTE: THIS IS NOT A HELP THREAD, ITS SIMPLE

Change directory it reads from here:
 
Last edited:

Adil

DevBest CEO
May 28, 2011
1,276
713
Is it not simple enough for you to understand?
 

What it does is waits for the connection of the user & displays the page, if its not found it redirects you to a 404 error
I can understand it just fine. What I'm saying is a good tutorial would explain what the code is doing. Yours, therefore, is not a good tutorial.
 

Users who are viewing this thread

Top