所以,我正在用 C# 開發一個客戶端應用程式,它連接到一個服務器端應用程式(也是用 C# 撰寫的)。首先,我只是想讓應用程式成功地相互通信。目前,我在同一臺設備上同時運行客戶端和服務器。
服務器端
在服務器端,我使用 aTcpListener來接受套接字,列印出它已連接用于除錯目的,接收請求并發送回應。代碼可以在下面找到:
服務器端代碼:
while (true)
{
// Accept a new connection
Socket socket = socketListener.AcceptSocket();
if (socket.Connected)
{
Console.WriteLine("\nClient Connected!!\n==================\nClient IP {0}\n", socket.RemoteEndPoint);
// Make a byte array and receive data from the client
byte[] receive = new byte[1024];
_ = socket.Receive(receive, receive.Length, 0);
// Convert byte to string
string buffer = Encoding.ASCII.GetString(receive);
string response = "Test response";
int numBytes = 0;
try
{
if (socket.Connected)
{
if ((numBytes = socket.Send(data, data.Length, 0)) == -1)
Console.WriteLine("Socket Error: cannot send packet");
else
Console.WriteLine("No. of bytes sent {0}", numBytes);
}
else
{
Console.WriteLine("Connection Dropped...");
}
}
catch (Exception e)
{
Console.WriteLine("An exception has occurred: " e.ToString());
}
}
}
客戶端
在客戶端,我使用 aTcpClient使用 IP 地址(在本例中為 127.0.0.1)連接到服務器,建立NetworkStream物件,發送請求并讀取回應。
客戶端代碼:
private static readonly TcpClient socket = new TcpClient();
private const string IP = "127.0.0.1";
private const int PORT = 46495;
static void Main(string[] args)
{
try
{
socket.Connect(IP, PORT);
}
catch (Exception)
{
Console.WriteLine("Error connecting to the server.");
return;
}
NetworkStream stream = socket.GetStream();
stream.ReadTimeout = 2000;
string request = "Test Request";
byte[] bytes = Encoding.UTF8.GetBytes(request);
stream.Write(bytes, 0, bytes.Length);
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
try
{
string response = reader.ReadToEnd();
Console.WriteLine(response);
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
輸出
On the server side, everything appears to be fine. The client connects successfully with the expected IP address, I get the expected request, and the correct response appears to have been sent successfully.
The client-side is where it gets more complicated. Where I would expect the "Test Response" response, instead I get a SocketException that from what I understand indicates a timeout??? The full output can be found below:
System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or an established connection failed because the connected host has failed to respond...
---> System.Net.Sockets.SocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or an established connection failed because the connected host has failed to respond.
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.StreamReader.ReadBuffer()
at System.IO.StreamReader.ReadToEnd()
at Client.Client.Main(String[] args) in C:\Dev\Project Orange Sunshine\Project Orange Sunshine\Client\Client.cs:line 38
What I have tried
To begin I wanted to ensure that my server was in fact sending a response in the first place. To test this, I tried accessing the server application through a web browser. Sure enough, I got a blank page with the expected "Test Response" text in the top left corner. This, to me, indicates my server application is working as expected.
通過一些谷歌搜索,我找到了類似問題的各種答案,指出 Windows Defender 防火墻很可能阻止了正在使用的埠。出于測驗目的,我嘗試完全禁用專用網路(例如我所在的網路)的防火墻。不幸的是,這并沒有改變任何事情。
我覺得我遺漏了一些明顯的東西,任何輸入都將不勝感激。
干杯!
uj5u.com熱心網友回復:
StreamReader.ReadToEnd()on aNetworkStream只會在到達流的“結束”時回傳,這在您的示例中不會發生;因此,StreamReader超時。
您應該通過使用較低級別的NetworkStream.Read方法從流中讀取來解決此問題:
var buffer = new byte[4096];
var bytesRead = stream.Read(buffer, 0, buffer.Length);
Console.WriteLine("Read {0} bytes", bytesRead);
string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine(response);
為了使這個測驗程式更健壯,您還需要引入“框架”,即服務器向客戶端指示它可以停止讀取的某種方式。這可以是終止符后綴,例如\r\nHTTP 使用的,或者預先發送以告訴客戶端要讀取多少位元組的長度前綴。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/360426.html
