0
我有一個python服務器和一個c#
客戶端之間的套接字連接,所以我試圖在客戶端定義一個布爾變量_status
,我在其中存儲連接的狀態(true或false)。我試過下面的代碼,但它不起作用;它總是返回一個錯誤的狀態,它有什麼問題?除此之外,還有其他好主意嗎?如何在套接字服務器和客戶端之間建立連接檢查器?
C#代碼:
public string ReceiveStatus()
{
sc.SetAddress("127.0.0.1");
sc.SetPort("20015");
sc.ServerConnect();
return sc.ReceiveQuery();
}
new Thread(() =>
{
var task = Task.Run(() => ReceiveStatus());
Thread.CurrentThread.IsBackground = true;
while(true)
{
sc.SendQuery("Are you here?");
if (task.Wait(TimeSpan.FromSeconds(1)))
{
if (task.Result == "Yes")
{
_status = true;
}
else
{
_status = false;
}
}
else
{
_status = false;
}
}
}).Start();
Python代碼:
while True:
try:
msg = ReceiveQuery(client)
if msg == "Are you here?":
SendQuery("Yes",client)
except Exception as e:
print ('an exception has been generated')
這個想法很好; ping協議(echo request/echo reply)是檢查連接的方式。當'task.Wait'後面的Python返回時'task.Result'的值是多少? – phd
'task.Result'的值'not yet calculated' –
你能提供'ReceiveStatus()'的代碼嗎? –