Reputation: 31
I recently built a server for one of my project. The server works with TCP connection. (5 devices comunicate with it simultaniously). Foreach device that connects to it i then create a new grid row with informations recieved. My problem is that if i have the clients turned on before the server is started the server is not able to handle the incoming connection rush and crashes. I need to start it few times before it finally fires on.
Unfortunetly i am not able to reproduce the error at my home to debug it. Is there any app which would be able to always try connecting to the server and when it finally succeds send a string over the network to it?
Upvotes: 0
Views: 324
Reputation: 31
In the end i wrote my app for this purpose. The app is very primitive. It just tries to reconect all the time it is not connected to the server and when it succeeds it sends connection string to the server and reads answer.
Here is the code if someone would like to utilize it: (for more connections at once just run more instances of this app or change the code aproprietly)
https://pa ste bin(.)com / g0wcJXh7 (i am sorry but i just wasnt able to paste all of the code inside the codeblock - it always put there just a part of it)
static TcpClient client;
static string ipAdress = "10.10.2.29";
static int port = 11800;
static string cnnMess;
static string junkMess;
static Byte[] bytes;
static Byte[] bytes_junk;
static void Main(string[] args)
{
//initializing variables
Random r = new Random();
cnnMess = string.Format("CNN?AA:BB:CC:DD:{0}!", r.Next(10, 99));
bytes = Encoding.UTF8.GetBytes(cnnMess);
junkMess = "JUNK!";
bytes_junk = Encoding.UTF8.GetBytes(junkMess);
while (true)
{
try
{
client.GetStream().Write(bytes_junk, 0, bytes_junk.Length); //App tries to send junk packet to the server (used to determine wether the connection still exist)
Thread.Sleep(50); //Put the thread to sleep to minimize the trafic
}
catch //if the sending fails it means that the client is no longer connected --> reconnect
{
Connect();
}
}
}
static void Connect()
{
client = new TcpClient();
try
{
client.Connect(ipAdress, port);
}
catch { }
int count = 0;
while (!client.Connected)
{
Thread.Sleep(500);
count++;
if(count >= 5)
{
try
{
client.Connect(ipAdress, port);
}
catch { }
count = 0;
Console.WriteLine("Connection Failed - retrying");
}
}
var writer = new StreamWriter(client.GetStream());
var reader = new StreamReader(client.GetStream());
client.GetStream().Write(bytes, 0, bytes.Length);
Console.WriteLine(cnnMess);
while (client.GetStream().DataAvailable)
{
Console.Write(client.GetStream().ReadByte());
}
Console.WriteLine();
}
Upvotes: 1