Socket Server Program in C#

Learn how to create a socket server in C#? By Nidhi Last updated : April 03, 2023

Creating a socket server

Here, we will create a socket server program, that accepts socket client connections, and then we can send or receive data in a network.

C# program to create a socket server

The source code to create a socket server is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Socket Server Program in C#

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();
  }
}

Output

Server is listening on port 15001
Waiting for incoming connections..
Received Data...
Hello
Data sent to received client
Press any key to continue . . .
Socket Server Program in C#

Explanation

In the above program, we created a socket server on the localhost with 15001 port. Here, server is listening to accept client connections and receive data from the server and send data to the server. To test the program, here we used the most common network test utility (Hercules), then we connect to our server using Hercules and send data "Hello" using Hercules then our server program sends acknowledge data "I have received data" message to the Hercules tool.

C# Socket Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.