TcpClient creation seem to be very slow. Can I cache those?
I have program where client peers communicate with each other via TCP-IP. When one client does something he will signal other clients one by one that this happened. Here is a code I use to send data across:
public static string SendDirect(string data, string hostName, int portNumber)
{
string responseData;
try
{
var client = new TcpClient(hostName, portNumber);
Stream s = client.GetStream();
var sw = new StreamWriter(s) { AutoFlush = true };
sw.WriteLine(data);
s.Close();
client.Close();
s.Dispose();
sw.Dispose();
responseData = "OK";
}
catch (SocketException ex)
{
responseData = ex.Message;
}
开发者_如何学运维 return responseData;
}
Line
var client = new TcpClient(hostName, portNumber);
can be very slow at times for some machines. For example, in my home network it takes like 2 or 3 seconds. Can you see how it's real bad with 15 clients.
I was wondering how expensive or if even possible to not Close client every time and keep 30-40 of them open at all times? I assume some mechanism to check to make sure they alive and to make sure they all closed properly need to be coded but I wonder if idea itself is correct..
Thanks!
Nothing should keep or limit you from creating more than one client/connection at a time. Actually initiating and closing tons of connections might trigger different security stuff (trying to fend of a possible DDOS attack or whatever). You might as well speed up the process resolving host names before and caching those. It doesn't necessarily have to be the object creation that slows you down actually.
The OS might throttle the number of pending connections per second (think 10 per second under Windows) but other than that there shouldn't be any issues. You shouldn't open/close connections for single commands anyway in my opinion. You should think about keeping both open, the TcpClient
as well as the StreamWriter
. Just ensure you flush once you're done writing your packet. To improve performance you should think about manual flushing, especially if there's is more than one command/packet to be sent to each client as each packet will take the minimum TCP window size (usually something around 1492-1500 bytes).
精彩评论