问题
(Before I start I know this title is awful if someone could think of a better name I'd love it)
I ran out of ideas to program, and found a post listing some things, so I made a simple local chat server. The server runs fine until I attempt to connect (via tcpClient)
The code from the client side is as follows:
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
Where the IP is my IPV4 static address.
On the server side:
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
When I attempt to connect the client, the server throws this
I do not understand why this is happening. Any assistance would be greatly appreciated.
回答1:
This is not correct:
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
ReceiveBufferSize
represents the internal buffer size used by the TCP socket, you're not supposed to use that in your code (there's also no need to call CInt()
, as it is already an Integer).
You already have your own buffer, which's length you are supposed to specify:
networkStream.Read(bytesFrom, 0, bytesFrom.Length)
The third parameter indicates the maximum number of bytes that you can receive in one Read()
call. Obviously this can't exceed your buffer's length, which is why you need to give it exactly that (or a smaller value, if you want to read a more specific amount of bytes).
来源:https://stackoverflow.com/questions/51355713/recievebuffersize-outofrangeexception-net