i have a problem :
My model is 1 Server serving lots Clients at the same time using TCP socket model. Codes usually work fine and never throw any exception, but sometime a connection between Server and a Client gose like this :
+)Client sends successfully data to Server (i know this because of using WireShark to catch every packets on Server's side)
+)Server socket.Receive(buffer) displays none of the datas above. (why tho?) //its a loop for receiving, so it has to be some datas after a zero-receive right? but looks like it stops receiving like forever.
+)Server sends data to Client (it sends usually, often per 500ms)
+)Client still able to receive datas from Server
And the circle continues like that.
i need to know why Server keeps "refusing"(idk) datas from Client like that while the connection looks fine?
Here is method Send i use for both sides : Socket.Send(Encoding.UTF8.GetBytes("Message$");
Here is the method Receive that i use for both sides, note that every messages end with "$" to separate them on other side.
int Signal(Socket s, byte[] b)
{
int k = 0;
try { k = s.Receive(b); return k; } catch { return 0; }
}
void Receiverr(Socket s){
new thread(()=>
{byte[] byteReceive = new byte[1024];
Array.Clear(byteReceive, 0, byteReceive.Length);
while (s.Connected)
{
string msg = "";
int n = Signal(s, byteReceive);
if (n == 0) { Array.Clear(byteReceive, 0, byteReceive.Length); continue; }
msg = Encoding.UTF8.GetString(byteReceive);
textBox2.Text += "n = " + n.ToString() + Environment.NewLine; // i use this to see if any byte that i could miss
msg = msg.Replace("\0", "");
string[] arrray_save = msg.Split('$');
foreach (string message in arrray_save)
{
//do my work
}
Array.Clear(byteReceive, 0, byteReceive.Length); continue;
}
try{s.Shutdown(SocketShutdown.Both); s.Close();}
catch{}
}
}){isBackGround = true}.Start();
I have suffered this for weeks :(, sorry for bad English, any help ill be appreciate.
Edited(05/24/2018) Here is my new code to make sure the data is correct to receive but the problem remains
byte[] data_save = new byte[1024]; int index = 0;
while (s.Connected)
{
int n = s.Available;
if (n == 0) { continue; }
byte[]byteReceive = new byte[n];
s.Receive(byteReceive);
byteReceive.CopyTo(data_save, index);
index += byteReceive.Length;
string test = Encoding.UTF8.GetString(data_save).Replace("\0", "");
if (test[test.Length - 1] != '$') { continue; }
textBox2.Text += test + Environment.NewLine;
Array.Clear(data_save, 0, data_save.Length);
index = 0;
string[] array_save = test.Split('$');
foreach (string message in array_save)
{
//do my work
}
}try { s.Shutdown(SocketShutdown.Both); s.Close();} catch { }