我在用PDA设备连接蓝牙称进行通讯,总是时不时的报 The operation is not allowed on non-connected sockets. ,后来加了一个Thread.Sleep(500); 解决了此问题
根据我的分析,原因是蓝牙创建连接后,停止半秒后,可以避免此错误。
大 致代码如下:
protected BluetoothDeviceInfo device = null;
protected BluetoothClient client = null;
Stream peerStream = null;
///蓝牙名
string blueName = BGLms.Handset.Code_JM.Configuration.XmlConfiguration.Instance.BlueName;
///蓝牙密码
string bluePwd = BGLms.Handset.Code_JM.Configuration.XmlConfiguration.Instance.BluePwd;
/// <summary>
/// Conn连接蓝牙
/// </summary>
public void loadConnectService()
{
try
{
if(client==null)
client = new BluetoothClient();
BluetoothDeviceInfo[] devices = client.DiscoverDevices(); //获取蓝牙设备扫描的所有服务湍
foreach (BluetoothDeviceInfo d in devices)
{
if (d.DeviceName == blueName)
{
device = d;
break;
}
}
// device = devices[0];
if (!device.Connected)//创建客户端连接对象
{
client.SetPin(device.DeviceAddress, bluePwd); //密码
client.Connect(device.DeviceAddress, BluetoothService.SerialPort);
}
}
catch (Exception ex)
{
if (peerStream != null)
{
peerStream.Dispose();
}
if (client != null)
{
client.Close();
}
MessageBox.Show("Error:" + ex.Message);
}
}
<p> /// <summary>
/// 获取数据
/// </summary>
private void GetMac()
{
StringBuilder resultdata = new StringBuilder();
//string errorMsg = "";
try
{
int I = 0;
Thread.Sleep(500); //关键代码
if (peerStream == null)
peerStream = client.GetStream();
#region MyRegion
while (true) //因为我这边蓝牙服务端是连续发送模式,所以通过此方法获取最新的通讯数据;
{
byte[] buffer = new byte[4096];
// Read Data
if (peerStream.CanRead)
{
peerStream.Read(buffer, 0, 4096);
// Convert Data to String
string data = System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, 4096);
data = data.Substring(1, data.Length - 1);
string[] arraystr = data.Split('=');
if (arraystr.Length < 512) //判断是不否读完
{
for (int i = arraystr[arraystr.Length - 2].Length - 1; i >= 0; i--)
{
resultdata.Append(arraystr[arraystr.Length - 2][i].ToString());
}
break;
}
}
if (I > int.MaxValue)
{
break;
}
I++;
}
#endregion
}
catch (Exception ex)
{
if (peerStream != null)
{
peerStream.Close();
peerStream.Dispose();
}
if (client != null)
{
client.Close();
client.Dispose();
}
return;
}</p><p> }</p>