サーバー クライアント アプリケーションを開発しています。どのサーバーとクライアントが同じホスト マシン上で実行されているか。ホストには 2 つの NIC があります。サーバーは 1 つの NIC の IP で実行されており、クライアントは他の NIC の IP にバインドされています。サーバーとクライアントのそれぞれのコードは次のとおりです。
サーバーコード:
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)
{ }
}
}
}
}
クライアントコード
パブリック クラス 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");の次の 3 行を置き換えます。IPEndPoint ipLocalEndPoint = 新しい IPEndPoint(ipAddress, 8000); TcpClient tcpclnt = 新しい TcpClient(ipLocalEndPoint); TcpClientで tcpclnt = new TcpClient(); 正常に動作しています。
また
クライアントが別のマシンで実行されている場合も、正常に動作しています。