I'm developing a C # Dll that works with Asynchronous TCP Socket for developing some tools I'm working on, the problem appears when the client receives many messages in a short period, in which case the messages are in JSON, so the server sends me only one JSON message per view, but the client gets 2 or 3 together, causing an Exception when trying to turn JSON into Object. Being that, if I send the server to send a message every second, everything happens well, but my system depends on more messages per second.
NOTE: The Server is done in C ++ with QT.
CLIENT:
public void connect(Action<Message> callback, string ip, int porta){
this.callback = callback;
this.ip = ip;
this.porta = porta;
try{
this.ipadress = new IPEndPoint (IPAddress.Parse (this.ip), this.porta);
this.client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.client.BeginConnect (this.ipadress, new AsyncCallback (ConectCallback), null);
}catch(Exception ex){
this.conected = false;
lastExeception = ex;
}
}
void ReceiveCallback(IAsyncResult IA){
String json_string = "";
if (isConnected ()) {
try {
int received = client.EndReceive (IA);
Array.Resize (ref _buffer, received);
json_string = Encoding.UTF8.GetString (_buffer);
Console.WriteLine(json_string);
Message msg = JsonConvert.DeserializeObject<Message> (json_string);
callback_sender (msg);
Array.Resize (ref _buffer, client.ReceiveBufferSize);
if (isConnected ())
client.BeginReceive (_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback (ReceiveCallback), null);
} catch (JsonException erro) {
lastExeception = erro;
} catch (Exception ex) {
lastExeception = ex;
}
}
}
SERVER:
void MyClient::readyRead() {
qDebug() << "MyClient::readyRead()";
QString msg = socket->readAll();
qDebug() << msg;
socket->write(msg.toUtf8());
}