我在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')
虽然我不知道socket连接对象的实现
sc
,但我在代码中看到了一些问题:ReceiveStatus()
包含连接套接字和通过套接字接收数据。你应该把它分成连接和接收两部分。你知道吗ReceiveStatus()
是在任务中启动的,因此有可能在连接套接字之前调用sc.SendQuery("Are you here?");
。你知道吗SendQuery()
,而在任务中只调用一次ReceiveQuery()
。任务一结束,你就再也看不到新的信息了。你知道吗相关问题 更多 >
编程相关推荐