为什么我收到BeginReceive大小(第3个参数)方法的错误?
但是BUFFER_SIZE它永远不会更大(以长度计)然后是常数值(它的2048字节)。
这是我的代码:
public void Send(byte[] byteData, M.StateObject _stateObj, Socket client)
{
// Begin sending the data to the remote client(s):
client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendData), _stateObj);
}
void SendData(IAsyncResult ar)
{
try
{
M.StateObject stateObj = (M.StateObject)ar.AsyncState;
Socket client = stateObj.server;
byte[] data = stateObj.data;
int bytesSent = client.EndSend(ar);
client.BeginReceive(data, 0, M.StateObject.BUFFER_SIZE, SocketFlags.None, new AsyncCallback(ReceiveData), stateObj);
allDone.Set();
}
catch (Exception ex)
{
OnMessageShowing(ex.Message);
}
}
private void ClientLogging(object _data, M.StateObject _stateObj)
{
M.UserData client = _data as M.UserData;
if (client != null)
{
//setting properties:
client.bConnectred = true;
// 1. add client to list of clients:
ClientAddingRemoving(_stateObj, client, true);
// 2. showing welcome on server
OnMessageShowing(client.ServerNotifying());
// 3. refreshing the list of clients on server`s main form
OnClientsListRefreshing(bll.ClientsListCreating(listOfClients));
// 4. send welcome note to all clients:
byte[] bytesToSend = M.SerializeServer.Login_WelcomeToAllClients(client);
bytesToSend = M.BytesArrayGetSet.BytesSending_Set(bytesToSend);
SendToAll(bytesToSend, _stateObj.server);
// 5. send list of all users to logged client:
bytesToSend = M.SerializeServer.Login_ToLoggedClient(bll.ListOfAllUsers(listOfClients));
bytesToSend = M.BytesArrayGetSet.BytesSending_Set(bytesToSend);
Send(bytesToSend, _stateObj, _stateObj.server);
//6. send new client to list of all other clients:
bytesToSend = M.SerializeServer.Login_ToAllClients(client);
bytesToSend = M.BytesArrayGetSet.BytesSending_Set(bytesToSend);
SendToAll(bytesToSend, _stateObj.server);
}
}
private void SendToAll(byte[] data, Socket _socket)
{
foreach (M.StateObject stObj in listOfClients.Keys) //dictionary<StateObject, Client>, Client is a custom client class
{
Send(data, stObj, _socket);
}
}
这是StateObject类:
public class StateObject
{
public Socket Server;
public const int BUFFER_SIZE = 2048;
public byte[] data = new byte[BUFFER_SIZE];
}
也许多次调用Send()方法?我是否必须使用“ManualResetEvent”委托来阻止或执行其他操作?我真的不知道该怎么做。
答案 0 :(得分:2)
将M.StateObject.BUFFER_SIZE
替换为stateObj.data.Length
,不知何故data
小于BUFFER_SIZE
。
此外,我看到你将数据输出到一个数组但不对它做任何事情。我会建议改变这个
byte[] data = stateObj.data;
int bytesSent = client.EndSend(ar);
client.BeginReceive(data, 0, M.StateObject.BUFFER_SIZE, SocketFlags.None, new AsyncCallback(ReceiveData), stateObj);
到这个
int bytesSent = client.EndSend(ar);
client.BeginReceive(stateObj.data, 0, stateObj.data.Length, SocketFlags.None, new AsyncCallback(ReceiveData), stateObj);
并查看是否可以解决您的错误。
另外我注意到你的BeginSend正在传递状态对象blob。您用于发送数据的数组stateObj.data
吗?如果是这样,是否使用新的stateObj
对象多次调用BeginSend?如果它们都共享相同的状态对象,则可以在当前接收写入的同时读取下一个发送读取。