我正在开发一个服务器客户端应用程序。哪个服务器和客户端在同一台主机上运行。主机有两个网卡。服务器在其中一个网卡的 ip 上运行,客户端已绑定到另一个网卡的 ip。服务器和客户端各自的代码如下。
服务器代码:
namespace Server { class Program { static void Main(string[] args) { Console.WriteLine("服务器正在运行并等待.....");
// 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)
{ }
}
}
}
}
客户代码
公共类 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)
{}
}
}
什么代码在做什么并不重要。只有连接部分是关注点。
当我使用没有任何参数的构造函数“TcpClient”时。我的意思是替换以下三行客户端 IPAddress ipAddress = IPAddress.Parse("192.0.0.5"); IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 8000); TcpClient tcpclnt = new TcpClient(ipLocalEndPoint); 使用 TcpClient tcpclnt = new TcpClient(); 它工作正常。
或者
当客户端在不同的机器上运行时,它也可以正常工作。