RecieveBufferSize 超出范围异常 (.NET)

RecieveBufferSize OutOfRangeException (.NET)

(在我开始之前我知道这个标题很糟糕,如果有人能想到一个更好的名字我会喜欢它)

我运行出于编程的想法,发现了一个post列出了一些东西,所以我做了一个简单的本地聊天服务器。服务器运行良好,直到我尝试连接(通过 tcpClient)

客户端代码如下:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    readData = "Connected."
    Msg()
    clientSocket.Connect("xxx.xxx.xx.xxx", 8888)
    serverStream = clientSocket.GetStream()

    Dim outStream As Byte() = Encoding.ASCII.GetBytes(TextBox1.Text & "$")
    serverStream.Write(outStream, 0, outStream.Length)
    serverStream.Flush()

    Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf GetMessage)
    ctThread.Start()
End Sub

其中IP是我的IPV4静态地址。

在服务器端:

Dim serverSocket As TcpListener = New TcpListener(ip, 8888)
    Dim clientSocket As TcpClient
    Dim counter As Integer = 0
    serverSocket.Start()
    Msg("Server started.")
    While (True)
        counter += 1
        clientSocket = serverSocket.AcceptTcpClient()

        Dim bytesFrom(10024) As Byte
        Dim dataFromClient As String

        Dim networkStream As NetworkStream = clientSocket.GetStream()
        networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
        dataFromClient = Encoding.ASCII.GetString(bytesFrom)

        dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"))

        clientsList(dataFromClient) = clientSocket

        Msg(dataFromClient & "joined the server.")
        Dim client as new handleClient
        client.startClient(clientSocket, dataFromClient, clientsList)
    End While

当我尝试连接客户端时,服务器抛出 this

我不明白为什么会这样。如有任何帮助,我们将不胜感激。

这是不正确的:

networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))

ReceiveBufferSize 表示 TCP 套接字使用的 internal 缓冲区大小,您不应在代码中使用它(也无需调用 CInt(), 因为它已经是一个整数).

您已经有了自己的缓冲区,您应该指定其长度:

networkStream.Read(bytesFrom, 0, bytesFrom.Length)

第三个参数表示您可以在一个Read() 调用中接收的最大字节数。显然这不能超过你的缓冲区的长度,这就是为什么你需要准确地给它(或者一个更小的值,如果你想读取更具体的字节数)。