0% found this document useful (0 votes)
13 views

NetworkProgramming

This is my client server application network in c sharp and WCF Documentation.

Uploaded by

Kashaf Nawaz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

NetworkProgramming

This is my client server application network in c sharp and WCF Documentation.

Uploaded by

Kashaf Nawaz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

A Simple Example of a Client-Server

Application Using the `System.Net`


Library In C#
This is a basic example to demonstrate how to create a simple client-server application using the
`System.Net` library in C#.
This example includes a server that listens for incoming connections and a client that connects to the
server and sends a message.

Server Code

First, let's create the server that listens for incoming connections:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

public class Server


{
public static void Main()
{
Task.Run(() => StartServer());
Console.WriteLine("Press Enter to quit...");
Console.ReadLine();
}

public static void StartServer()


{
var listener = new TcpListener(IPAddress.Any, 5000);
listener.Start();
Console.WriteLine("Server started, waiting for connections...");

while (true)
{
var client = listener.AcceptTcpClient();
Task.Run(() => HandleClient(client));
}
}

public static void HandleClient(TcpClient client)


{
var buffer = new byte[1024];
var stream = client.GetStream();

int bytesRead = stream.Read(buffer, 0, buffer.Length);


string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received: {message}");

string response = "Hello from server!";


byte[] responseBytes = Encoding.UTF8.GetBytes(response);
stream.Write(responseBytes, 0, responseBytes.Length);

client.Close();
}
}

Client Code

Next, let's create the client that connects to the server and sends a message:

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

public class Client


{
public static void Main()
{
try
{
var client = new TcpClient("127.0.0.1", 5000);
var stream = client.GetStream();

string message = "Hello from client!";


byte[] messageBytes = Encoding.UTF8.GetBytes(message);
stream.Write(messageBytes, 0, messageBytes.Length);

var buffer = new byte[1024];


int bytesRead = stream.Read(buffer, 0, buffer.Length);
string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received: {response}");

client.Close();
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
}

Explanation

Server Code:
TcpListener: Listens for incoming connections on port 5000.
HandleClient: Handles each client connection in a separate task. Reads the incoming message and sends
a response back to the client.

Client Code:
TcpClient: Connects to the server at `127.0.0.1` on port 5000.
Send Message: Sends a message to the server and reads the response.

Running the Example

1. Start the Server: Run the server application first. It will start listening for incoming connections.
2. Run the Client: Run the client application. It will connect to the server, send a message, and print the
server's response.
Windows Communication Foundation
(WCF).
WCF provides a unified programming model for building service-oriented applications and supports a
variety of communication protocols, including HTTP, TCP, and MSMQ.

Example: Simple WCF Service

This example demonstrates how to create a simple WCF service and client. WCF is a powerful
framework for building distributed applications and is the recommended approach for replacing .NET
Remoting
Here's a basic example of a WCF service and a client:

Step 1: Define the Service Contract

Create a new class library project and define the service contract:

using System.ServiceModel;

namespace WcfService
{
[ServiceContract]
public interface ICalculatorService
{
[OperationContract]
double Add(double a, double b);
}
}

Step 2: Implement the Service

Implement the service contract in a class:


using System.ServiceModel;
using System.ServiceModel.Description;
namespace WcfService
{
public class CalculatorService : ICalculatorService
{
public double Add(double a, double b)
{
return a + b;
}
}
}

Step 3: Configure the Service

Create a configuration file (`Web.config` or `App.config`) to configure the service:


<system.serviceModel>
<services>
<service name="WcfService.CalculatorService">
<endpoint address="" binding="basicHttpBinding" contract="WcfService.ICalculatorService"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/CalculatorService"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

Step 4: Create the Client

Create a new console application project for the client:

using System;
using System.ServiceModel;
namespace WcfClient
{
class Program
{
static void Main(string[] args)
{
var address = new Uri("http://localhost:8000/CalculatorService");
var binding = new BasicHttpBinding();
var endpoint = new EndpointAddress(address);
var channelFactory = new ChannelFactory<ICalculatorService>(binding, endpoint);
var client = channelFactory.CreateChannel();

double result = client.Add(10, 5);


Console.WriteLine($"Result: {result}");
}
}
}

Explanation

1. Service Contract: Defines the operations the service will provide.


2. Service Implementation: Implements the service contract.
3. Service Configuration: Configures the service to use HTTP binding and sets the base address.
4. Client: Creates a client to consume the service.

You might also like