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()'的代码吗? –