[英]udp server respond on the basis of the request received from the udp client
[英]Why my server can not respond to the client's request from the webbrowser?
我正在使用C#進行嵌入式傳感器雲(客戶端-服務器)程序的工作,但據我所知存在一個問題,我需要您的幫助:D
在下面,您可以看到我的服務器端代碼以及我遇到的問題是,每當我在Debug模式下運行該程序時,一切都可以很好地工作,但是如果我像往常一樣運行它,從本地主機打開HTML文件的請求將無法正常工作,並且瀏覽器會向服務器發送一些空請求,並且無法繼續進行。
這是我的服務器端代碼:
private static void Listen()
{
IPAddress ipAddress = IPAddress.Any;
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8081);
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
Console.WriteLine("Waiting for Connection");
Socket handler = listener.Accept();
Console.WriteLine("connected");
NetworkStream stream = new NetworkStream(handler);
if (stream.DataAvailable)
{
Request req = new Request(stream);
Dictionary<string, string> header = new Dictionary<string, string>(req.Headers);
PluginManager ipm = new PluginManager();
IPlugin plug = SelectPlugin(ipm, req);
if (plug != null)
{
foreach (var item in header)
{
Console.WriteLine(item);
}
IResponse rep = plug.Handle(req);
rep.Send(stream);
Console.WriteLine("Success");
stream.Close();
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
else
{
IResponse resp = new Response()
{
StatusCode = 404,
ContentType = "text/html",
};
resp.Send(stream);
break;
}
}
else
{
Console.WriteLine("Data not Available");
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
這是我在調試模式下運行時得到的:
Waiting for Connection
connected
[get .../index.html HTTP/1.1]
[user-agent, Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134]
[accept-language, en-US,en;q=0.8,de-DE;q=0.6,de;q=0.4,fa;q=0.2]
[accept, text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]
[upgrade-insecure-requests, 1]
[accept-encoding, gzip, deflate]
[host, 8081]
[connection, Keep-Alive]
Success
在這里,當我正常運行時:
Waiting for Connection
connected
Data not Available
Waiting for Connection
套接字無法再監聽傳入的連接。 有人知道為什么嗎?
除了“異步還是同步”之外,您永遠不要使用DataAvailable
做出決策。 它不會告訴你的數據是否可用-它只是告訴你它是否適用現在 。 我懷疑調試模式會充分降低它的速度,以確保數據可用。 您應該改為進行讀取(選擇同步還是異步),讀取結果為非正數,表示流結束。
就是說:看來您已經編寫了可擴展到一個並發客戶端的服務器。 除非這是供本地使用,否則我建議不要在此處編寫您自己的服務器-從“ kestrel”(asp.net核心服務器)開始,並在那里實現自己的處理程序可能會更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.