Chat spam auto block for C# chat client

2019-08-30 11:24发布

问题:

I'm really new to C#, so Currently I'm working on this LAN messenger, for use at school. Code for the messenger itself, including server and client I have found on the internet, so I haven't programmed all of it myself. The very basic code, as sending and recieving messages has been copied. Anyways! Im having problems with people spamming the chat. The client contains connecting options, as well as a multiline textbox for all incoming messages, a textbox for writing a message and a send button to send the message itself. Is there a way to stop people from "spamming" the chat client? For example locking the "send message" textbox if a user sends like 5 messages in 2 seconds. How could this be done? It does not have to be locking the textbox, as long as it blocks the spamming user from sending more messages. Thank in advance

回答1:

The first thing to consider is never trust a client. This means that anyone that has access to your source code, or even knows the protocols that the server uses, can write their own client that sends spam messages all day long.

Assuming the spam is just coming from people using the client you provide, you can certainly count the number of messages sent in a given timeframe and disable the Send button if a threshold is exceeded.

Assuming this is using WinForms, the code to block the button would be something like:

btnSend.Enabled = false;

To keep track of the number of messages sent in recent history, you could create something like

List<DateTime> messageTimestamps;

and put timestamps in there.

When someone sends a message, do this:

  • Remove all entries from the list that are more than (say) 2 seconds old
  • Add the new entry to the list
  • If the list count > (say) 5, disable the Send button and discard this message

At that point you would need to start a timer to clear the blocked state. Have a look at

http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

to see how that works.



回答2:

Maybe have a counter count up each time a user sends a message, and if the counter gets to 5, do whatever you want to do to keep the user from sending another message. Then simply reset the counter every 2 seconds with a Timer object.

int spam = 0;
Timer timer = new Timer(2000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;

static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    spam = 0;
}

if (spam < 5)
{
    //send message as usual
    spam++;
}
else
    //notify user that sending messages has been disabled, please wait 'x' seconds to send another message