ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Advanced Programming
    CSI-415
    Progress0 / 55 topics
    Topics
    1. Visual Programming Basics2. Introduction to Events3. Fundamentals of Event-Driven Programming4. Message Handling5. User Interfaces6. Graphics Device Interface7. Painting and Drawing8. Windows Management9. Input Devices10. Resources11. String and Menu Resource12. Dialogs and Windows Controls13. Common Controls14. Dynamic Link Libraries (DLLs)15. Threads and Synchronization16. Network Programming17. Building Class Libraries at the Command Line18. Class Libraries19. Using References20. Assemblies21. Private Assembly Deployment22. Shared Assembly Deployment23. Configuration Overview24. Configuration Files25. Programmatic Access to Configuration26. Using SDK Tools for Signing and Deployment27. Metadata28. Reflection29. Late Binding30. Directories and Files31. Serialization32. Attributes33. Memory Management and Garbage Collection34. Threading and Synchronization35. Asynchronous Delegates36. Application Domains37. Marshal by Value38. Marshal by Reference39. Authentication and Authorization40. Configuring Security41. Code Access Security42. Code Groups43. Evidence44. Permissions45. Role-Based Security46. Principals and Identities47. Using Data Readers48. Using Data Sets49. Interacting with XML Data50. Tracing Event Logs51. Using the Boolean Switch and Trace Switch Classes52. Print Debugging Information with the Debug Class53. Instrumenting Release Builds with the Trace Class54. Using Listeners55. Implementing Custom Listeners
    CSI-415›Network Programming
    Advanced ProgrammingTopic 16 of 55

    Network Programming

    7 minread
    1,187words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,187
      Code examples0
      DifficultyIntermediate