【发布时间】:2018-01-18 00:22:40
【问题描述】:
所以我在 C# 中创建了一个在线聊天室,我在第 71 行遇到了这个错误。
System.ArgumentOutOfRangeException: '指定的参数超出了有效值的范围。'
我有一个客户端程序和一个服务器程序。这是客户端程序的代码。给我错误的行是星号。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
namespace ChatProgram
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new
System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;
static int maxUsage = 0;
string noName = "Anonymous";
int tick = 0;
public Form1()
{
InitializeComponent();
}
private void enterButton_Click(object sender, EventArgs e)
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(readRichTxt.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
readData = "Connected to server...";
msg();
clientSocket.Connect("127.0.0.1", 8888);
serverStream = clientSocket.GetStream();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
string nameTxt = nameTextBox.Text;
if (nameTxt == String.Empty)
{
nameTxt = noName;
tick = 1;
}
else
{
tick = 0;
}
readRichTxt.SelectionColor = Color.Red;
readRichTxt.AppendText("\n" + nameTxt + " has joined." + "\n");
++maxUsage;
sendButton.Enabled = true;
if (maxUsage == 3)
{
enterButton.Enabled = false;
}
}
private void getMessage()
{
while(true)
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[10025];
buffSize = clientSocket.ReceiveBufferSize;
***serverStream.Read(inStream, 0, buffSize);***
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
msg();
}
}
private void msg()
{
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(msg));
else
readRichTxt.Text = readRichTxt.Text + Environment.NewLine + " >> " + readData;
}
private void sendButton_Click(object sender, EventArgs e)
{
string nameTxt = nameTextBox.Text;
string userTyped = userTypeBox.Text;
if (userTyped == String.Empty)
{
return;
}
if (tick == 1)
{
readRichTxt.AppendText(noName + ": " + userTyped);
}
else
{
readRichTxt.AppendText(nameTxt + ": " + userTyped);
}
userTypeBox.Clear();
}
}
}
请帮忙,我现在完全被难住了。
【问题讨论】:
-
该错误出现在哪一行?
-
您将 inStream 声明为 10025 字节的数组。您尝试读取的流可能比这大,导致超出范围异常。相反,请在获得缓冲区长度后尝试将其声明为
new byte[buffSize]。