Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Networking

Introduction to Networking

Networking in .NET involves using classes and libraries that allow you to build and manage networked applications. .NET provides a robust set of tools for creating both client and server applications, including support for HTTP, TCP/IP, and more.

Using HttpClient for HTTP Requests

The HttpClient class is a powerful tool for making HTTP requests. It supports asynchronous operations and can be used to perform various types of HTTP requests, such as GET, POST, PUT, DELETE, etc.

Example: Making a GET Request


using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program {
    static async Task Main(string[] args) {
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/1");
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
    }
}
    

Creating a TCP Server

The TcpListener class in .NET allows you to create a TCP server that listens for incoming client connections. This is useful for creating server-side applications that communicate over TCP/IP.

Example: TCP Server


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

class Program {
    static async Task Main(string[] args) {
        TcpListener server = new TcpListener(IPAddress.Any, 13000);
        server.Start();
        Console.WriteLine("Server started...");

        while (true) {
            TcpClient client = await server.AcceptTcpClientAsync();
            NetworkStream stream = client.GetStream();
            byte[] buffer = new byte[1024];
            int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
            string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine($"Received: {message}");
            
            byte[] response = Encoding.UTF8.GetBytes("Message received");
            await stream.WriteAsync(response, 0, response.Length);
            client.Close();
        }
    }
}
    

Creating a TCP Client

The TcpClient class in .NET allows you to create a TCP client that connects to a server. This is useful for client-side applications that need to communicate with a server over TCP/IP.

Example: TCP Client


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

class Program {
    static async Task Main(string[] args) {
        TcpClient client = new TcpClient();
        await client.ConnectAsync("127.0.0.1", 13000);
        NetworkStream stream = client.GetStream();
        
        byte[] message = Encoding.UTF8.GetBytes("Hello, Server!");
        await stream.WriteAsync(message, 0, message.Length);
        
        byte[] buffer = new byte[1024];
        int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
        string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
        Console.WriteLine($"Received: {response}");
        
        client.Close();
    }
}
    

Using WebSockets

WebSockets provide a full-duplex communication channel over a single TCP connection. The System.Net.WebSockets namespace in .NET provides classes to work with WebSockets.

Example: WebSocket Client


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

class Program {
    static async Task Main(string[] args) {
        ClientWebSocket client = new ClientWebSocket();
        await client.ConnectAsync(new Uri("ws://echo.websocket.org"), CancellationToken.None);
        
        byte[] message = Encoding.UTF8.GetBytes("Hello, WebSocket!");
        await client.SendAsync(new ArraySegment<byte>(message), WebSocketMessageType.Text, true, CancellationToken.None);
        
        byte[] buffer = new byte[1024];
        WebSocketReceiveResult result = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        string response = Encoding.UTF8.GetString(buffer, 0, result.Count);
        Console.WriteLine($"Received: {response}");
        
        await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
    }
}
    

Conclusion

Networking in .NET is a vast topic with numerous classes and libraries to facilitate building robust and scalable networked applications. From simple HTTP requests to complex TCP servers and WebSocket communication, .NET provides a comprehensive set of tools to handle all your networking needs.