Networking and Web APIs

38.1 HttpClient

Use IHttpClientFactory in DI-based apps. Add resilience (retries, timeouts) with Polly / Microsoft.Extensions.Http.Resilience.

Imports System.Net.Http
Imports System.Net.Http.Json

Private Shared ReadOnly Http As New HttpClient() With {.BaseAddress = New Uri("https://jsonplaceholder.typicode.com/")}   ' reuse one instance

Public Async Function GetTodosAsync() As Task
    Dim todo = Await Http.GetFromJsonAsync(Of Todo)("todos/1")
    Console.WriteLine($"{todo.Id}: {todo.Title} (done: {todo.Completed})")

    Dim response = Await Http.PostAsJsonAsync("posts", New With {.title = "Hello", .body = "From VB", .userId = 1})
    response.EnsureSuccessStatusCode()
    Dim created = Await response.Content.ReadAsStringAsync()

    Http.DefaultRequestHeaders.Authorization = New Headers.AuthenticationHeaderValue("Bearer", token)
    Using req As New HttpRequestMessage(HttpMethod.Delete, "posts/1")
        Dim res = Await Http.SendAsync(req)
        Console.WriteLine(res.StatusCode)
    End Using
End Function

Public Class Todo
    Public Property Id As Integer
    Public Property Title As String
    Public Property Completed As Boolean
End Class

38.2 Sockets and TCP

Imports System.Net
Imports System.Net.Sockets

' Server
Dim listener As New TcpListener(IPAddress.Any, 9000)
listener.Start()
Using client = Await listener.AcceptTcpClientAsync(),
      stream = client.GetStream(),
      reader As New IO.StreamReader(stream),
      writer As New IO.StreamWriter(stream) With {.AutoFlush = True}
    Dim line = Await reader.ReadLineAsync()
    Await writer.WriteLineAsync("Echo: " & line)
End Using

' Client
Using client As New TcpClient()
    Await client.ConnectAsync("localhost", 9000)
End Using

38.3 Other Networking

Dns.GetHostEntry, Ping (System.Net.NetworkInformation), UdpClient, SmtpClient (obsolete for new development: use MailKit), WebSocket (ClientWebSocket), FTP (use FluentFTP), and SignalR clients.