We have web application , it works as Socket Listner. I wanted to check before the AcceptSocket , whether there is any Client Socket available to connect to this listener. I want to display a message if there is no Client Socket to connect and cancel send/receive of data.
For this issue I used Pending Method of TcpListener class, but this works for me partly.
It works well if remote is not available, it return false. But when remote is available then sometimes Pending () method returns false. I want it to return true when remote is available all the time.
This is my code: public bool Communicationcation() {
string strSiteID = "SiteID";
socket.Start();
if(!socket.Pending())
{
Console.WriteLine("Sorry, no connection requests have arrived");
return false;
}
else
{
client = socket.AcceptSocket();
if (client.Connected == true)
{
// int nSiteID = int.Parse(ConfigurationSettings.AppSettings.Get("SiteID"));
object dSiteID = GetSiteSetting(ref strSiteID);
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
WriteLog(string.Format("Connected with {0} at port {1}", clientep.Address, clientep.Port));
string strWelcome = STARTMESSAGE + "WHOAMI" + " " + dSiteID + " " + dSiteID + FINISHMESSAGE;
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(strWelcome);
int i = client.Send(data, data.Length, SocketFlags.None);
WriteLog(String.Format("Message sent {0} bytes!", i));
//Get reply from the Connected cleint.
byte[] bytes = new byte[1024];
i = client.Receive(bytes, bytes.Length, SocketFlags.None);
if (i != -1)
{
WriteLog(string.Format(System.Text.Encoding.UTF8.GetString(bytes)));
}
}
return true;
}
}
TcpListener class Pending method always returns false though Remote is running. If we run the code without debug.but when we debug the code then Pending method is inconsistent and returns some time false and some time true.