我正在开发服务器客户端应用程序 . 哪个服务器和客户端在同一主机上运行 . 主持人有两个网站 . 服务器正在其中一个nic的ip上运行,而客户端已绑定到其他nic的ip . 服务器和客户端的相应代码如下 .
Server Code:
namespace Server {class Program {static void Main(string [] args){Console.WriteLine(“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)
{}
}
}
什么代码并不重要 . 只有连接部分是关注点 .
当我使用构造函数"TcpClient"没有任何参数 . 我的意思是替换以下三行客户端IPAddress ipAddress = IPAddress.Parse("192.0.0.5"); IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress,8000); TcpClient tcpclnt = new TcpClient(ipLocalEndPoint);使用TcpClient tcpclnt = new TcpClient();它工作正常 .
要么
当客户端在不同的机器上运行时,它也正常工作 .
1 回答
后人:使用TcpClient()
(来源:https://msdn.microsoft.com/en-us/library/zc1d0e0f%28v=vs.110%29.aspx),这就是它起作用的原因 .
通过调用
TcpClient(IPEndpoint)
过载来分配 endpoints 会强制它到特定的NIC,地址和端口 . 如果从该IPEndpoint到服务器 endpoints 没有网络路由,则无法 Build 连接 . 除非涉及组合,否则在同一网络上的同一台机器上安装两个NIC通常被认为是不好的做法 .192.0.0.4
和192.0.0.5
是问题所在,并且将NIC放在具有它们之间路由的不同网络上将在是否指定客户端上的本地 endpoints 的情况下工作 .