4
I am for fun to develop a TCP server in C# that performs functions depending on the message that the connected client sends you, for now, I only managed to do what I want with functions that return strings, for this I have the following:
A dictionary that stores the string the message the user is supposed to send to the server so that the function he wants and the function in question is executed:
private Dictionary<string, Func<string>> stringFunctions = new Dictionary<string, Func<string>>();
A function that looks for the function the customer wants:
private string CheckCommands() {
for(int i = 0; i < stringFunctions.Count; i++)
if(stringFunctions.ContainsKey(rcvString))
return stringFunctions[rcvString].Invoke();
return "";
}
Realisation of demand within the communication loop with the customer:
string commandAnswer = CheckCommands();
if(commandAnswer != "") {
netStream.Write(Encoding.ASCII.GetBytes(commandAnswer), 0, Encoding.ASCII.GetBytes(commandAnswer).Length);
Console.WriteLine("Sent: {0}", commandAnswer);
} else {
netStream.Write(Encoding.ASCII.GetBytes("Could not find that command in our database"), 0, Encoding.ASCII.GetBytes("Could not find that command in our database").Length);
}
How do I put the function in the dictionary:
myFunctions.Add("test", new Func<string>(Test));
This all I presented works, but I wanted now to be able to use the same method but for void functions, is there any way similar to what I try to do? I still can’t get there.
Yes I know that my dictionary only accepts string functions, I just wanted to know how to change so that this other kind of functions as explained later. By the way, in your code snippets you continue to call a dictionary of type <string, Func<string>>. Anyway thanks, it helped a lot!
– André
Yeah, I forgot to change in both places.
– Maniero