I am developing a server client application. In which server and client are running on same host machine. The host has two nic. Server is running on the ip of one of the nic and client has been bound to ip of the other nic. Respective codes of server and client is below.
Server Code:
namespace Server { class Program { static void Main(string[] args) { Console.WriteLine("The Server is Run And Wait .....");
// Create Server Socket to recive
try
{
IPAddress ipAddress = IPAddress.Parse("192.0.0.4");
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 2700);
TcpListener Ls = new TcpListener(ipLocalEndPoint);
Ls.Start();
while (true)
{
Socket soc = Ls.AcceptSocket();
//soc.SetSocketOption(SocketOptionLevel.Socket,
// SocketOptionName.ReceiveTimeout,10000);
try
{
Stream s = new NetworkStream(soc);
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(s);
sw.AutoFlush = true; // enable automatic flushing
sw.WriteLine("{0} Number of employee", ConfigurationManager.AppSettings.Count);
while (true)
{
string name = sr.ReadLine();
Console.WriteLine("name {0}",name);
sw.WriteLine("entered name {0}", name);
if (name == "" || name == null) break;
string job = ConfigurationManager.AppSettings[name];
if (job == null) job = "No such employee";
sw.WriteLine(job);
}
s.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
soc.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
while (true)
{ }
}
}
}
}
Client Code
public class clnt {
public static void Main()
{
try
{
IPAddress ipAddress = IPAddress.Parse("192.0.0.5");
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 8000);
TcpClient tcpclnt = new TcpClient(ipLocalEndPoint);
Console.WriteLine("Connecting.....");
tcpclnt.Connect("192.0.0.4", 2700);
// use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (SocketException e)
{
Console.WriteLine("Error..... " + e.ErrorCode);
}
while(true)
{}
}
}
What code is doing not important. Only Connection part is point of concern.
When i am using constructor "TcpClient" without any parameter. I mean replace following three line of client IPAddress ipAddress = IPAddress.Parse("192.0.0.5"); IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 8000); TcpClient tcpclnt = new TcpClient(ipLocalEndPoint); with TcpClient tcpclnt = new TcpClient(); It is working fine.
or
When client is running on different machine then also it is working fine.