gpt4 book ai didi

c# - NetworkStream.Read() 不起作用并抛出 ArgumentOutOfRangeException

转载 作者:可可西里 更新时间:2023-11-01 02:57:49 26 4
gpt4 key购买 nike

只是想创建一个聊天服务器客户端

  1. 这是等待客户端连接的服务器(可选)*

        TcpListener serverSocket = new TcpListener(8888);
    int requestCount = 0;
    TcpClient clientSocket = default(TcpClient);
    serverSocket.Start();
    Console.WriteLine(" >> Server Started");
    clientSocket = serverSocket.AcceptTcpClient();
    Console.WriteLine(" >> Accept connection from client");
  2. 然后,客户端连接到服务器(可选)*

        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
    clientSocket.Connect("127.0.0.1", 8888);
  3. 然后,在客户端,我从 Windows 窗体发送消息,按钮单击事件执行此操作:

    NetworkStream serverStream = clientSocket.GetStream();
    byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
    serverStream.Write(outStream, 0, outStream.Length);
    serverStream.Flush();
    //this goes to the server ------> to the part (4)

    //returning from the server <------
    byte[] inStream = new byte[10025];
    serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
    string returndata = System.Text.Encoding.ASCII.GetString(inStream);
    textBox2.Text = "";
    textBox2.Focus();
  4. 最后,在服务器端,客户端请求的无限循环。这是我在 networkStream.Read() 上遇到问题的地方

    while ((true))
    {
    try
    {
    requestCount = requestCount + 1;
    NetworkStream networkStream = clientSocket.GetStream();
    byte[] bytesFrom = new byte[10025];
    if (networkStream.DataAvailable)
    {
    **networkStream.Read(bytesFrom, 0, (int) clientSocket.ReceiveBufferSize);**
    string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
    Console.WriteLine(" >> Data from client - " + dataFromClient);
    string serverResponse = "Last Message from client" + dataFromClient;
    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
    networkStream.Write(sendBytes, 0, sendBytes.Length);
    networkStream.Flush();
    Console.WriteLine(" >> " + serverResponse);
    }
    }
    catch (Exception ex)
    {
    Console.WriteLine(ex.ToString());
    }
    }

我逐步调试(在服务器和客户端上),一切正常,直到我进入 networkStream.Read() 方法,并抛出 ArgumentOutOfRangeException...拜托,任何人帮助我或告诉我错误在哪里。

*我说可选是因为 1. 和 2. 步骤很好(至少,我认为)

最佳答案

来自MSDN , ArgumentOutOfRangeException 表示 offsetcount 为负数(第 2 个和第 3 个参数),或者“size(count)”参数大于 buffer 的长度减去“偏移量”参数。

我会尝试传递 bytesFrom.Length 而不是 clientSocket.ReceiveBufferSize

关于c# - NetworkStream.Read() 不起作用并抛出 ArgumentOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40682437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com