I am trying to write a small server client code where the client sends a control message to the server to execute a job.
The program flow goes as such
1. client sends a control message and goes into wait till a return message is received.
2. server receives the message and sends an execution "success/failure" message to the client and busy waits till a shutdown(i.e. zero byte) message is received.
3. client receives the "success/failure" and sends a close socket message (zero byte shutdown.send) to server and goes into busy wait till it receives a shutdown message.
4. server receives the shutdown messages, sends a shutdown in return and releases the resources of the socket.
5. client receives the shutdown and releases the resources of the socket.
What I have tried:
the code is as follows
client side
try
{
sock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(remoteEP);
string sent_msg = "RESTART CCMCOM";
MessageLogTextBox.AppendText("Message sent at " + DateTime.Now + " : " + sent_msg + Environment.NewLine);
byte[] msg = Encoding.ASCII.GetBytes(sent_msg);
sock.Send(msg);
Thread.Sleep(500);
msg = new byte[1024];
sock.Receive(msg);
string received_msg = Encoding.ASCII.GetString(msg).Trim();
MessageLogTextBox.AppendText("Message received at " + DateTime.Now + " : " + received_msg + Environment.NewLine);
MessageLogTextBox.AppendText(Environment.NewLine);
MessageLogTextBox.AppendText(Environment.NewLine);
sock.Shutdown(SocketShutdown.Send);
while (sock.Receive(msg) != 0) ;
sock.Disconnect(false);
sock.Close();
}
catch (Exception ex)
{
MessageLogTextBox.AppendText(ex.Message);
}
server side
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
outputFile.WriteLine("DCA1_CCMCOM_Remote_Restart_Service started at : {0}", DateTime.Now);
while (true)
{
handler = listener.Accept();
string data = null;
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
if (bytesRec != 0)
{
data = Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("RESTART CCMCOM") > -1)
{
ServiceController sc = new ServiceController("DCA1_CCMCOM");
if (sc != null && sc.Status.Equals(ServiceControllerStatus.Running))
sc.Stop();
Thread.Sleep(10);
sc.Refresh();
while (sc != null && !sc.Status.Equals(ServiceControllerStatus.Stopped))
sc.Refresh();
sc.Start();
outputFile.WriteLine("Service restarted at : {0}", DateTime.Now);
handler.Send(Encoding.ASCII.GetBytes("Service Restarted"));
while ( handler.Receive(bytes) != 0) ;
handler.Shutdown(SocketShutdown.Send);
handler.Disconnect(true);
handler.Close();
}
}
else
{
handler.Shutdown(SocketShutdown.Send);
handler.Disconnect(true);
handler.Close();
}
}
}
catch (Exception e)
{
outputFile.WriteLine("DCA1_CCMCOM_Remote_Restart_Service stopped at : {0} due to {1}", DateTime.Now, e.Message);
handler.Shutdown(SocketShutdown.Both);
handler.Disconnect(true);
handler.Close();
}
where am i going wrong?