I'm trying to code a chat application using async sockets in C#. The problem that I'm facing is that when the client runs a command to list the users logged in the server, the server should send the list to the client and then the client would update the list. The problem is that the client is not receiving the entire data from the server. And then, when converting the data to a form of processed data (i.e a string), it can not, and acts like the data is null.
When the server receives a 'List' command, it send back a 'List' command with a message.
Piece of the server code:
case Data.Command.List:
//Send the names of all users in the chat room to the new user
msgToSend.cmdCommand = Data.Command.List;
msgToSend.strMessage = null;
msgToSend.strName = null;
//Collect the names of the user in the chat room
foreach (Cliente client in clientes)
{
//To keep things simple we use asterisk as the marker to separate the user names
msgToSend.strMessage += client.strName + "*";
}
// DEBUG: The server is setting the message correctly
Console.WriteLine(msgToSend.cmdCommand);
Console.WriteLine(msgToSend.strMessage);
Console.WriteLine(msgToSend.strName);
message = msgToSend.ToByte();
// DBEUG: Printing on the screen the array of data that is being sent to the client.
foreach (var item in message)
{
Console.WriteLine(item);
}
//Send the name of the users in the chat room
clientSocket.BeginSend(message, 0, message.Length, SocketFlags.None,
new AsyncCallback(OnSend), clientSocket);
break;
}
When I'd check the data being sent by the server and the data received by the client, the array is different.
a sample of the last run that i did
Server:
3
0
0
0
0
0
0
0
9
0
0
0
77
101
117
85
115
101
114
49
42
Client: 3 0 0 0 8 0 0 0 0 0 0 0 77 101 117 85 115 101 114 49
A piece of the class that converts the Data into strings:
public Data(byte[] data)
{
//The first four bytes are for the Command
this.cmdCommand = (Command)BitConverter.ToInt32(data, 0);
//The next four store the length of the name
int nameLen = BitConverter.ToInt32(data, 4);
//The next four store the length of the message
int msgLen = BitConverter.ToInt32(data, 8);
//This check makes sure that strName has been passed in the array of bytes
if (nameLen > 0)
this.strName = Encoding.UTF8.GetString(data, 12, nameLen);
else
this.strName = null;
//This checks for a null message field
if (msgLen > 0)
this.strMessage = Encoding.UTF8.GetString(data, 12 + nameLen, msgLen);
else
this.strMessage = null;
}
I do not know why the client is receiving less/different data than the server is sending. Any help?