我有一个使用TcpListener的服务器应用程序。它侦听连接,当它获取连接时,StreamReader读取流并将流传递给根据请求提供回复的方法。回复是一个从.html文件中读取的字符串。我的客户端应用程序获取回复并将字符串设置为webBrowser1.Documenttext属性。问题:我的服务器似乎没有收到请求,但两个应用程序似乎相互连接(退出服务器会在客户端计算机上产生错误)。这是我的代码:
服务器:
static void Main(string[] args)
{
Console.WriteLine("Application Started");
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
IPAddress hostIP = IPAddress.Parse(localIP);
TcpListener listener = new TcpListener(hostIP, 1986);
string request;
StreamWriter swStream;
StreamReader srStream;
listener.Start();
while (listener.Pending() == true)
{
listener.AcceptTcpClient();
Console.WriteLine("New Client Accepted");
TcpClient client = listener.AcceptTcpClient();
srStream = new StreamReader(client.GetStream());
request = srStream.ReadToEnd();
Console.WriteLine("Stream has been read.");
swStream = new StreamWriter(client.GetStream());
string responseText = handleRequest(request);
swStream.Write(responseText);
}
Console.ReadLine();
}
客户端:
private void getInfo(string request)
{
string dispCode;
string hostName;
TcpClient client;
//set IP & host
serverIP = (IPAddress.Parse(SGAClient.Properties.Settings.Default.ServerIP));
hostName = (Dns.GetHostEntry(serverIP).ToString());
client = new TcpClient();
client.Connect(serverIP, 1986);
StreamWriter swStream = new StreamWriter(client.GetStream());
swStream.Write(request);
StreamReader srStream = new StreamReader(client.GetStream());
//sets the value of the display code
string response = srStream.ReadToEnd();
swStream.Close();
srStream.Close();
client.Close();
//displays the information from the server
displayInfo(response);
}
答案 0 :(得分:1)
listener.AcceptTcpClient();
Console.WriteLine("New Client Accepted");
TcpClient client = listener.AcceptTcpClient();
您接受客户(丢弃它)...然后再次尝试接受它。