我构建了一个快速的小脚本来从我为手机创建的应用程序中获取数据并将其放在文本框中,它与此代码完美配合:
private void workerVoid()
{
string receivedDataString = null;
listenSock.Listen(3);
acceptedSock = listenSock.Accept();
listenSock.Bind(new IPEndPoint(IPAddress.Any, 5665));
while(shouldRun)
{
while (listenSock.SendBufferSize != 0)
{
Buffer = new byte[listenSock.SendBufferSize];
int byteCount = acceptedSock.Receive(Buffer);
byte[] byteFormatted = new byte[byteCount];
for (int byteCounter = 0; byteCounter < byteCount; byteCounter++)
{
byteFormatted[byteCounter] = Buffer[byteCounter];
}
receivedDataString = Encoding.ASCII.GetString(byteFormatted);
setTextDelegate sTD = new setTextDelegate(setText);
reqFormVar.Invoke(sTD, new object[] { receivedDataString });
}
}
}
使用workerVoid作为一个线程。然而,这完全适用,当连接的设备(我的手机)断开连接时,线程完全停止运行(我得到线程..已经在visual studio中退出)并且我的设备在此之后无法连接,即使我有一个应该永远运行的while循环。
如何在没有线程退出的情况下断开连接后,我的设备可以重新连接?
由于
答案 0 :(得分:0)
您的代码可能会抛出异常,导致忽略while循环,以避免这种情况。 在try catch中围绕内部while循环,并在try catch块中移动减速,如下所示:
var shouldRun = true;
while(shouldRun)
{
try
{
string receivedDataString = null;
listenSock.Listen(3);
acceptedSock = listenSock.Accept();
listenSock.Bind(new IPEndPoint(IPAddress.Any, 5665));
while (listenSock.SendBufferSize != 0)
{
...
}
}
catch
{
}
}