2017-09-14 45 views
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')  
+0

這個想法很好; ping協議(echo request/echo reply)是檢查連接的方式。當'task.Wait'後面的Python返回時'task.Result'的值是多少? – phd

+0

'task.Result'的值'not yet calculated' –

+0

你能提供'ReceiveStatus()'的代碼嗎? –

回答

1

雖然我不知道你的插座連接對象sc實施我看到你的代碼中的一些問題:

  • ReceiveStatus()包含連接套接字和通過套接字接收數據。你應該把它分成連接和接收。
  • 由於ReceiveStatus()在任務中啓動,因此可能在套接字連接之前調用sc.SendQuery("Are you here?");
  • 雖然在無限循環中調用SendQuery(),但在任務中只調用ReceiveQuery()一次。一旦任務結束,你將永遠不會再讀取新的信息。
+0

這很有幫助! –

相關問題