如何在 F# 中使用 TcpListener NetworkStream?

How to use TcpListener NetworkStream in F#?

我正在尝试从此处 https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(v=vs.110).aspx 移植 C# 示例代码,但在读取数据部分时遇到了问题。 Byte[] bytes = new Byte[256]; F#应该怎么写?

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

let ipAddress = IPAddress.Parse("127.0.0.1")
let port = 1000

let tcpListener = TcpListener(ipAddress, port)

let rec listen() =
    printfn "Listening..."
    let tcpClient = tcpListener.AcceptTcpClient()
    printfn "Connected!"
    let networkStream = tcpClient.GetStream()
    // port Byte[] bytes = new Byte[256]; to F#
    listen()

try
    tcpListener.Start()
    listen()
with
    | error -> printfn "%s" error.Message

Console.Read() |> ignore

您可以使用 Array.zeroCreate 函数创建一个空数组。将其添加到您的代码中,listen 函数将如下所示:

let rec listen() =
    let tcpClient = tcpListener.AcceptTcpClient()
    let networkStream = tcpClient.GetStream()
    let buffer = Array.zeroCreate 256
    let read = networkStream.Read(buffer, 0, 256)
    // Do something with 'buffer' and 'read'
    listen()