Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

C# Server:


Sure, I can provide a simple explanation of how to create a C# server along with an example. In C#, you can create a server using the System.Net.Sockets namespace, which provides classes for implementing sockets. Here's a basic example of a TCP server in C#:

Example

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

class TCPServer
{
static void Main(string[] args)
{
// Set the IP address and port number
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
int port = 8888;

// Create a TCP/IP socket
TcpListener server = new TcpListener(ipAddress, port);

try
{
// Start listening for client requests
server.Start();

Console.WriteLine("Server started. Waiting for connections...");

while (true)
{
// Accept the client connection
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client connected.");

// Get the network stream
NetworkStream stream = client.GetStream();

// Buffer for reading data
byte[] buffer = new byte[1024];
int bytesRead;

// Read incoming data
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
// Convert the data to a string
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received: {dataReceived}");

// Echo back the data to the client
byte[] responseData = Encoding.ASCII.GetBytes(dataReceived);
stream.Write(responseData, 0, responseData.Length);
}

// Close the client connection
client.Close();
Console.WriteLine("Client disconnected.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
finally
{
// Stop listening for client requests
server.Stop();
Console.WriteLine("Server stopped.");
}
}
}

This server listens on IP address "127.0.0.1" (localhost) and port 8888. It accepts incoming TCP client connections, reads data from the client, echoes the data back to the client, and then closes the connection. You can modify the IP address and port number according to your requirements.

To use this example, create a new C# console application project in Visual Studio or any other C# development environment, and paste this code into your Program.cs file. Then, you can run the program, and it will start listening for incoming connections.

Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java