如何在套接字服务器和客户端之间建立连接检查程序?

时间:2017-09-14 16:20:34

标签: c# python sockets

我在python服务器和c#客户端之间有一个套接字连接,所以我试图在客户端定义一个布尔变量_status,我在其上存储了状态连接(真或假)。我已经尝试过下面的代码,但它不起作用;它总是返回虚假状态,有什么不对吗?还有什么好的想法比这更好吗?

c#c​​ode:

        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')      

1 个答案:

答案 0 :(得分:1)

虽然我不知道套接字连接对象sc的实现,但我发现代码中存在一些问题:

  • ReceiveStatus()包含连接套接字和通过套接字接收数据。你应该把它分成连接和接收。
  • ReceiveStatus()在任务中启动时,可能会在连接套接字之前调用sc.SendQuery("Are you here?");
  • 在无限循环中调用SendQuery()时,ReceiveQuery()在任务中只调用一次。任务结束后,您将永远不会再次阅读新信息。