2017-09-14 44 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

这很有帮助! –

相关问题