ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCSI-415Network Programming
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CSI-415

    Advanced Programming

    Progress0 / 55 done
    Topics55
    1Visual Programming Basics2Introduction to Events3Fundamentals of Event-Driven Programming4Message Handling5User Interfaces6Graphics Device Interface7Painting and Drawing8Windows Management9Input Devices10Resources11String and Menu Resource12Dialogs and Windows Controls13Common Controls14Dynamic Link Libraries (DLLs)15Threads and Synchronization16Network Programming17Building Class Libraries at the Command Line18Class Libraries19Using References20Assemblies21Private Assembly Deployment22Shared Assembly Deployment23Configuration Overview24Configuration Files25Programmatic Access to Configuration26Using SDK Tools for Signing and Deployment27Metadata28Reflection29Late Binding30Directories and Files31Serialization32Attributes33Memory Management and Garbage Collection34Threading and Synchronization35Asynchronous Delegates36Application Domains37Marshal by Value38Marshal by Reference39Authentication and Authorization40Configuring Security41Code Access Security42Code Groups43Evidence44Permissions45Role-Based Security46Principals and Identities47Using Data Readers48Using Data Sets49Interacting with XML Data50Tracing Event Logs51Using the Boolean Switch and Trace Switch Classes52Print Debugging Information with the Debug Class53Instrumenting Release Builds with the Trace Class54Using Listeners55Implementing Custom Listeners
    7 min read
    Topic 16 of 55
    Topic Study Note Illustration
    16

    Network Programming

    Network programming in C# involves writing software that communicates over a network. Whether you're building a web service, client-server application, or a peer-to-peer network, C# provides powerful...

    Network Programming in C#

    Network programming in C# involves writing software that communicates over a network. Whether you're building a web service, client-server application, or a peer-to-peer network, C# provides powerful tools to work with networks. C# uses the System.Net and System.Net.Sockets namespaces to facilitate network operations, allowing you to work with both high-level protocols like HTTP and low-level protocols like TCP and UDP.

    Below is an in-depth look at network programming in C#, including the different types of communication (TCP, UDP), and examples of creating client-server applications.


    1. Overview of Network Programming in C#

    Network programming involves two or more computers communicating over a network (such as the Internet, LAN, or WAN). The System.Net namespace in C# offers classes to deal with common network tasks, including the TcpClient, TcpListener, UdpClient, and Socket classes. These classes provide easy-to-use methods for sending and receiving data.

    In C#, network programming typically involves:

    • Client-Server Communication: One application (the server) listens for incoming requests, while another application (the client) sends requests to the server.
    • Socket Programming: Sockets are used to establish connections between clients and servers. You can work with both connection-oriented protocols (TCP) and connectionless protocols (UDP).

    2. Key Concepts

    Sockets

    A socket is an endpoint for sending or receiving data across a computer network. In C#, the Socket class in the System.Net.Sockets namespace is used to work with low-level network connections. The socket allows communication between two devices over a network.

    • TCP (Transmission Control Protocol) provides reliable, connection-oriented communication.
    • UDP (User Datagram Protocol) is faster but provides no guarantee of reliability, order, or data integrity.

    Network Protocols

    1. TCP (Transmission Control Protocol):

      • TCP is a connection-oriented protocol, which means a connection must be established before communication can happen.
      • It ensures the delivery of data and guarantees that packets arrive in the same order they were sent.
      • C# provides the TcpClient and TcpListener classes to work with TCP.
    2. UDP (User Datagram Protocol):

      • UDP is connectionless and does not guarantee delivery, ordering, or error-checking.
      • It is faster than TCP and is used in scenarios where speed is more important than reliability (e.g., real-time video streaming, DNS, or online gaming).
      • C# provides the UdpClient class to work with UDP.

    3. Creating a TCP Client-Server Application in C#

    TCP Server (Listening for Clients)

    A TCP server listens for incoming client connections. It uses the TcpListener class to bind to a specific IP address and port number.

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    class TcpServer
    {
        static void Main()
        {
            // Set up the server to listen on port 8080
            TcpListener listener = new TcpListener(IPAddress.Any, 8080);
            listener.Start();
    
            Console.WriteLine("Waiting for a client to connect...");
            // Accept incoming client connections
            TcpClient client = listener.AcceptTcpClient();
            Console.WriteLine("Client connected!");
    
            // Get the network stream to send/receive data
            NetworkStream stream = client.GetStream();
    
            // Receive a message from the client
            byte[] buffer = new byte[256];
            int bytesRead = stream.Read(buffer, 0, buffer.Length);
            string clientMessage = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received from client: " + clientMessage);
    
            // Send a response to the client
            string response = "Hello, client!";
            byte[] responseBytes = Encoding.UTF8.GetBytes(response);
            stream.Write(responseBytes, 0, responseBytes.Length);
    
            // Close the connection
            client.Close();
            listener.Stop();
        }
    }
    
    • TcpListener: This class is used to listen for incoming TCP connections.
    • AcceptTcpClient(): Accepts an incoming client connection.
    • NetworkStream: Used to send and receive data over the TCP connection.

    TCP Client (Connecting to Server)

    The client connects to the server using the TcpClient class. After establishing a connection, the client can send data and receive a response.

    using System;
    using System.Net.Sockets;
    using System.Text;
    
    class TcpClientApp
    {
        static void Main()
        {
            // Connect to the server at localhost on port 8080
            TcpClient client = new TcpClient("127.0.0.1", 8080);
            NetworkStream stream = client.GetStream();
    
            // Send a message to the server
            string message = "Hello, server!";
            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            stream.Write(messageBytes, 0, messageBytes.Length);
    
            // Receive the server's response
            byte[] buffer = new byte[256];
            int bytesRead = stream.Read(buffer, 0, buffer.Length);
            string serverResponse = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received from server: " + serverResponse);
    
            // Close the connection
            client.Close();
        }
    }
    
    • TcpClient: This class is used to connect to a remote server.
    • NetworkStream: Allows the client to send and receive data over the connection.

    4. Creating a UDP Client-Server Application in C#

    UDP Server (Listening for Clients)

    Unlike TCP, UDP is connectionless, meaning there’s no need to establish a connection before sending data. The server listens for incoming UDP packets.

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    class UdpServer
    {
        static void Main()
        {
            // Set up the server to listen on port 8080
            UdpClient udpServer = new UdpClient(8080);
            Console.WriteLine("Server is listening on port 8080...");
    
            // Receive data from a client
            IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
            byte[] data = udpServer.Receive(ref clientEndPoint);
    
            // Convert data to string
            string receivedMessage = Encoding.UTF8.GetString(data);
            Console.WriteLine($"Received from client: {receivedMessage}");
    
            // Send a response back to the client
            string response = "Hello, UDP Client!";
            byte[] responseBytes = Encoding.UTF8.GetBytes(response);
            udpServer.Send(responseBytes, responseBytes.Length, clientEndPoint);
    
            // Close the UDP server
            udpServer.Close();
        }
    }
    
    • UdpClient: The UdpClient class is used to receive and send UDP datagrams.
    • Receive(): Receives UDP packets from any client.
    • Send(): Sends a UDP packet to a client.

    UDP Client (Sending Data to Server)

    The client sends a message to the server, and the server responds back.

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    class UdpClientApp
    {
        static void Main()
        {
            // Set up the UDP client and specify the server's IP and port
            UdpClient udpClient = new UdpClient();
            IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
    
            // Send a message to the server
            string message = "Hello, UDP Server!";
            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            udpClient.Send(messageBytes, messageBytes.Length, serverEndPoint);
    
            // Receive a response from the server
            byte[] serverResponse = udpClient.Receive(ref serverEndPoint);
            string response = Encoding.UTF8.GetString(serverResponse);
            Console.WriteLine("Received from server: " + response);
    
            // Close the UDP client
            udpClient.Close();
        }
    }
    
    • UdpClient: Used for sending and receiving UDP packets.
    • Send(): Sends a message to the server.
    • Receive(): Receives a response from the server.

    5. Advanced Topics in Network Programming

    Asynchronous Network Programming

    In C#, asynchronous network programming can be done using async/await or the Begin/End method pair. This is important when working with network operations that might block the main thread, such as waiting for a connection or sending/receiving large amounts of data.

    Example using async/await with TCP:

    using System;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading.Tasks;
    
    class AsyncTcpClient
    {
        static async Task Main()
        {
            TcpClient client = new TcpClient("127.0.0.1", 8080);
            NetworkStream stream = client.GetStream();
    
            string message = "Hello, async server!";
            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            await stream.WriteAsync(messageBytes, 0, messageBytes.Length);
    
            byte[] buffer = new byte[256];
            int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
            string serverResponse = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received from server: " + serverResponse);
    
            client.Close();
        }
    }
    

    SSL/TLS Encryption

    For secure communication over the network,

    ← Previous topic 15
    Threads and Synchronization
    Next topic 17 →
    Building Class Libraries at the Command Line

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.2kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Advanced Programming