NetworkProgramming
NetworkProgramming
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;
while (true)
{
var client = listener.AcceptTcpClient();
Task.Run(() => HandleClient(client));
}
}
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;
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.
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.
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:
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);
}
}
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();
Explanation