Search code examples
c#tcpf#tcpclienttcpserver

Why does TcpClient.Connected() show true after being closed by TcpListener? F#


So I'm trying to learn more about TCP through F# and when I close the connection from the listener's end after 1 second, it still shows true that the client is connected on the client's end.

Server:

open System.Net
open System.Net.Sockets
open System.Threading

let tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1000)

let rec listen() =
    printfn "Listening..."

    let tcpClient = tcpListener.AcceptTcpClient()
    printfn "Connected!"

    Thread.Sleep(1000)

    tcpClient.Close()
    printfn "Disconnected."

    listen()

tcpListener.Start()
listen()

Client:

open System
open System.Net.Sockets
open System.Threading

let connect() =
    let tcpClient = new TcpClient("127.0.0.1", 1000)
    printfn "Connected!"

    let rec loop() =
        Thread.Sleep(100)

        let isConnected = tcpClient.Connected

        if isConnected = false then
            printfn "Disconnected."
        else
            loop()

    Console.Read() |> ignore

connect()

Solution

  • It seems that you're never calling the loop function, so it never actually checks the connection.