C# Program to Create a Socket Server

You are currently viewing C# Program to Create a Socket Server

C# program to create a socket server

//C# program to create a socket server

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

class SocketServer
{
    static void Main(string[] args)
    {
        string IP   = "127.0.0.1";
        int PORT    = 15001;
        int len     = 0;

        byte[] byteArray  = new byte[256];
        byte[] sendbytes = new byte[256];

        ASCIIEncoding encoding;
        Socket        socket;

        IPAddress LocalHostIP = IPAddress.Parse(IP);
        TcpListener listner = new TcpListener(LocalHostIP, PORT);
        
        listner.Start();

        Console.WriteLine("Server is listening on port "+ PORT);
        Console.WriteLine("Waiting for incoming connections..");

        socket = listner.AcceptSocket();
        len = socket.Receive(byteArray);
        
        Console.WriteLine("Received Data...");
        for (int i = 0; i < len; i++)
        {
            Console.Write(Convert.ToChar(byteArray[i]));
        }
        
        encoding = new ASCIIEncoding();
        sendbytes = encoding.GetBytes("I have received data");
        socket.Send(sendbytes);

        Console.WriteLine("\nData sent to received client");

        socket.Close();
        listner.Stop();
    }
}
Server is listening on port 15001
Waiting for incoming connections..
Received Data...
Hello
Data sent to received client
Press any key to continue . . .

Ranjith Kumar

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply