Da Curse Da Curse - 1 month ago 6
C# Question

C# Sockets How to know when certain data is sent

I made a simple "Reverse Shell" in C#, up to 5 clients can connect to a server
The client needs to input a command, I made a command that allows clients to communicate with each other, the problem is when for example client 3 sends a message to client 1, It will show this message only after client 1 will press enter, How come I make it display no matter what?

This is the code I use to recieve data and display it:

while (true)
{
Console.Write("> ");
string cmd = Console.ReadLine();
byte[] buffer = Encoding.UTF8.GetBytes(cmd);

client.Send(buffer, 0, buffer.Length, 0);

byte[] recievedBuffer = new byte[1024];
int rec = client.Receive(recievedBuffer);
byte[] data = new byte[rec];
Array.Copy(recievedBuffer, data, rec);

Console.WriteLine(Encoding.UTF8.GetString(data));

}

Answer

I think the problem is happening because in your loop you first must send data and only after that you can receive any.

while (true) 
{
    //must send data
    client.Send(buffer, 0, buffer.Length, 0);

    //then receive
    int rec = client.Receive(recievedBuffer);
}

By pressing enter client1 actually sends data according to your program and then he is free to finally get the messgae client3 sent him.

Because of this implementation you must first send data and then must receive and so on, this is very limited behavior.

If you want your client to get the messages the time they are sent you need to use another thread to check in some intervals if messages have been arrived, something like a timer can be useful.

Just be careful and use a proper synchronization to prevent race conditions between your threads if you decided to work in a multithreaded environment.

Another option is to go async and implememnt something based on Asynchronous Client Socket idea.

Comments