I have created socket program in C# console application using Asynchronous Server Socket. I referred example from below site to listen to particular port on server. https://msdn.microsoft.com/en-us/library/fx6588te(v=vs.100).aspx
My application code is.
static void Main(string[] args)
{
Process thisProc = Process.GetCurrentProcess();
StartListening();
}
public static void StartListening()
{
byte[] bytes = new Byte[iSize];
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint( ipAddress , Convert.ToInt32 (ConfigurationSettings.AppSettings["Port"].ToString()));
Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("Waiting for a connection on..." + ConfigurationSettings.AppSettings["Port"].ToString());
try
{
listener.Bind(localEndPoint);
listener.Listen(1000);
while (true)
{
allDone.Reset();
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
allDone.WaitOne();
}
}
catch (Exception e)
{
writeToLogFile(string.Format("Client {0}\t StartListening Exception ={1}", DateTime.Now.ToString() + ": ", e.Message + " Stack=" + e.StackTrace), "E");
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
try
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
StateRecord++;
handler.ReceiveTimeout = 0;
handler.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
state.workSocket = handler;
if (handler != null)
{
state.IP = ((IPEndPoint)handler.RemoteEndPoint).Address;
state.port = ((IPEndPoint)handler.RemoteEndPoint).Port;
}
Thread jobFile3 = new Thread(delegate() { writeToLogFile(string.Format("Client {0}{1} {2}\t Connected", DateTime.Now + ": " + state.IP, ":", state.port ), "E"); });
jobFile3.Start();
handler.BeginReceive(state.buffer, 0, iSize, 0, new AsyncCallback(ReadCallback), state);
}
catch (Exception e)
{
Thread jobFileEx = new Thread(delegate() { writeToLogFile(string.Format("Client {0}\t socket Exception at AcceptCallback ={1}", DateTime.Now.ToString() + ": " , e.Message + " Stack=" + e.StackTrace), "E"); });
jobFileEx.Start();
}
}
public static void ReadCallback(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
string ipAdd = state.IP.ToString();
string portNo = state.port.ToString();
SocketError errorCode;
int bytesRead = handler.EndReceive(ar, out errorCode);
if (state.Record == 1 && bytesRead == 0 && state.MaxTry <= 3)
{
state.MaxTry++;
Thread.Sleep(500);
handler.BeginReceive(state.buffer, 0, iSize, 0, new AsyncCallback(ReadCallback), state);
}
else if (bytesRead > 0)
{
string Recd = state.Record.ToString();
StringBuilder ByteData = new StringBuilder();
foreach (byte byt in state.buffer)
{
ByteData.Append(byt.ToString() + ",");
}
string SaveByteData = ByteData.ToString();
Thread jobFile3 = new Thread(delegate() { writeToLogFile(string.Format("Client {0}{1} {2}\t Length = {3}/{4}", DateTime.Now + ": " + ipAdd, ":", portNo, bytesRead, Recd + " Data=" + SaveByteData), "E"); });
jobFile3.Start();
Thread job = new Thread(delegate() { SaveMetaData(SaveByteData, ipAdd, portNo); });
job.Start();
state.Record++;
handler.BeginReceive(state.buffer, 0, iSize, 0, new AsyncCallback(ReadCallback), state);
}
else
{
if (( errorCode == SocketError.TimedOut || errorCode == SocketError.ConnectionReset ) && state.MaxTry <= 3 )
{
state.MaxTry++;
Thread.Sleep(100);
handler.BeginReceive(state.buffer, 0, iSize, 0, new AsyncCallback(ReadCallback), state);
}
if (handler != null && handler.Connected)
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
StateRecord--;
}
Thread jobFile = new Thread(delegate() { writeToLogFile(string.Format("Client {0}{1} {2}\t Disconnected, Status = {3}", DateTime.Now + ": " + ipAdd, ":", portNo, errorCode.ToString() + " byteRead=" + bytesRead + " Total Client =" + StateRecord), "E", true); });
jobFile.Start();
if (StateRecord > 25)
{
StateRecord = 20;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
}
catch (Exception e)
{
StateObject state = (StateObject)ar.AsyncState;
string ipAdd = state.IP.ToString();
string portNo = state.port.ToString();
Socket handler = state.workSocket;
if (handler != null && handler.Connected)
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
StateRecord--;
}
Thread jobFileEx = new Thread(delegate() { writeToLogFile(string.Format("Client {0}\t socket Exception ={1}", DateTime.Now.ToString() + ": " + ipAdd + ": " + portNo, e.Message + " Stack=" + e.StackTrace), "E"); });
jobFileEx.Start();
}
}
My client is device (like vehicle tracking device) which sends data periodically using AT command through GPRS service. Most of the time data received on server by my console application but some time data not received by my application.
When data send by device it gets reply "Send OK" from SIM card but my console application on server doesn't receive any thing.
I have checked client, server communication using wireshark utility which is network analyzer tool. We monitor the port & found some times ACK between client & server is missing. This data is received on wireshark but not on c# console application.
Can you please let us know what setting I missed in program or on server ?
Please refer screen of captured TCP data. Here 216 is our server IP & device IP is 106.
http://i.stack.imgur.com/WOjjs.png[
^]