我想创建一个异步套接字。服务器端应按时处理客户端请求,而不应设置在队列中。我阅读了更多内容,并在下面的链接中写了类似的代码。在服务器端是正确的,我没有任何错误或问题,但是在客户端,当我想接收数据时,对于第一次接收到的数据,一切都很好,但是当第二次调用ReceiveCallback时,我得到以下错误:
Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
链接是:
https://stackoverflow.com/questions/14974404/socket-programming-multiple-client-one-server
我在ReceiveCallback方法中的代码是:
private void ReceiveCallback(IAsyncResult asyncResult)
{
try
{
StateObject state = (StateObject)asyncResult.AsyncState;
Socket client = state.workSocket;
int bytesRead = 0;
if (client != null)
bytesRead = client.EndReceive(asyncResult);
if (bytesRead > 0)
{
//string content = state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead)).ToString();
Buffer.BlockCopy(state.buffer, 0, _imageBuff, _totBytesRead, bytesRead);
_totBytesRead += bytesRead;
//if (content.IndexOf(Cache.EndOfMessage, StringComparison.Ordinal) > -1)
if (_totBytesRead < state.ImageSize)
{
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, ReceiveCallback, state);
//if (state.sb.Length > 1)
//{
// _response = state.sb.ToString();
//}
}
else
{
newMsgReceived(_imageBuff);
receiveDone.Set();
}
}
}
catch (Exception ex)
{
Log.CreateLog(Kit.Journal.Logger.Enums.LogType.Error, ex.Message, "ReceiveCallback in MonitoringSocket has error!");
}
}
该错误是我的方法中“ Blockcopy”的一部分。
我要测试我的应用程序,以便在发布之前处理计算机中的某些客户端,我编写了以下代码。我使用了线程。
private void BtnConfirm_Click(object sender, RoutedEventArgs e)
{
//ImgDataGrid.Items.Clear();
var pc = new PersianCalendar();
var fromDate = pc.ToDateTime(_fromYear, _fromMonth, _fromDay, 0, 0, 0, 1);
var toDate = pc.ToDateTime(_toYear, _toMonth, _toDay, 0, 0, 0, 1);
byte[] fileNameObj = null;
var thread = new Thread(() =>
{
fileNameObj = ServiceUtility.GetImageFileNames(fromDate, toDate);
var fileNameListStrTemp = "";
var fileNameListStr = new List<string>();
if (fileNameObj != null && fileNameObj.Length > 0)
{
fileNameListStrTemp = Kit.Utility.ZipTask.Unzip(fileNameObj);
}
if (fileNameListStrTemp != null && !string.IsNullOrEmpty(fileNameListStrTemp))
{
fileNameListStr = fileNameListStrTemp.Split('|').ToList();
FillDataGridView(fileNameListStr);
}
else
{
MessageBox.Show("");
}
});
thread.Start();
byte[] fileName = null;
var thread1 = new Thread(() =>
{
fileName = ServiceUtility.GetImageFileNames(fromDate, toDate);
var fileNameListStrTemp = "";
var fileNameListStr = new List<string>();
if (fileName != null && fileName.Length > 0)
{
fileNameListStrTemp = Kit.Utility.ZipTask.Unzip(fileName);
}
if (fileNameListStrTemp != null && !string.IsNullOrEmpty(fileNameListStrTemp))
{
fileNameListStr = fileNameListStrTemp.Split('|').ToList();
FillDataGridView(fileNameListStr);
}
else
{
MessageBox.Show("");
}
});
thread1.Start();
}
我现在很困惑。为了处理服务器端客户端的某些请求,我应该在服务器端线程化,还是可以像上面的代码那样编写?我在客户端的代码不正确或在BtnConfirm_click中测试我的代码不正确?