- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在使用 32feet.Net
库编写一个 C# 控制台应用程序,它创建两个线程来搜索和连接到不同的蓝牙设备,然后打开 TCP 套接字以便可以将数据传递到通过网络连接的设备。我知道这种情况听起来很奇怪,但一位资深同事要求我这样做。
我的代码似乎只连接了一个设备就可以正常工作,尽管蓝牙连接有时会在来回传递几条消息后断开。但是,有时一旦第二个设备连接,我就会收到一条错误消息,提示 System.net.sockets.socketexception a connection attempt failed because the connected party did not properly respond
,其他时候代码只是退出而没有抛出任何异常(exception)。
我想知道是什么原因造成的,我看到 32feet.Net
库可以支持多个连接。我想知道我是否犯了一些错误,因为我是 C#
、.Net
甚至 Windows 的新手,并且之前从未编写过任何基于蓝牙的代码.
程序.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace BluetoothManager
{
class Program
{
static void Main(string[] args)
{
BTManager rover_btm = new BTManager();
BTManager base_btm = new BTManager();
base_btm.Port = 0xba5e;
rover_btm.Port = 17825;
base_btm.Name = "Base";
rover_btm.Name = "Rover";
base_btm.match = (args.Length >= 1 && args[0] != "") ? args[0] : "dev1";
rover_btm.match = (args.Length >= 2 && args[1] != "") ? args[1] : "dev2";
Console.WriteLine("Base Station match: " + base_btm.match);
Console.WriteLine("Rover match: " + rover_btm.match);
Thread Base = new Thread(new ThreadStart(base_btm.HandleThread));
Thread Rover = new Thread(new ThreadStart(rover_btm.HandleThread));
Base.Start();
Rover.Start();
Base.Join();
Rover.Join();
Console.Read();
}
}
}
BTManager.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Ports;
using InTheHand.Net.Sockets;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using Microsoft.Win32;
using System.IO;
namespace BluetoothManager
{
class BTManager
{
private static BluetoothDeviceInfo[] peers;
private BluetoothClient client;
private bool _isConnected = false;
private string _match;
private const string defpin = "0000";
private TcpListener tcpListener;
private int _port;
private string _name = "Not Named";
public string Name
{
get { return _name; }
set { _name = value; }
}
public int Port
{
get { return _port; }
set { _port = value; }
}
public bool IsConnected
{
get { return _isConnected; }
private set { _isConnected = value; }
}
public string match
{
get { return _match; }
set { _match = value; }
}
public BTManager()
{
client = new BluetoothClient();
}
public void HandleThread()
{
BluetoothDeviceInfo device;
while (!this.findDevice(out device)) ;
Console.WriteLine("About to pair");
int count = 0;
int max = 5;
while ((!(BluetoothSecurity.PairRequest(device.DeviceAddress, defpin))) && count < max)
{
Console.WriteLine("Pairing Failed, retrying");
count++;
Thread.Sleep(100);
}
if (count == max)
{
HandleThread();
}
else
{
Console.WriteLine("Paired..Beginning connect");
client.BeginConnect(device.DeviceAddress, BluetoothService.SerialPort, this.callback, client);
}
}
private void callback(IAsyncResult result)
{
client.EndConnect(result);
this.tcpListener = new TcpListener(IPAddress.Loopback, _port);
this.tcpListener.Start();
TcpClient TcpClient = this.tcpListener.AcceptTcpClient();
NetworkStream networkStream = TcpClient.GetStream();
Stream bluetoothStream = client.GetStream();
byte[] fromNetwork = new byte[1024];
byte[] fromBluetooth = new byte[1024];
while (client.Connected && TcpClient.Connected)
{
try
{
if (networkStream.CanRead)
{
Array.Clear(fromNetwork, 0, 1024);
networkStream.Read(fromNetwork, 0, 1024);
Console.WriteLine(Encoding.ASCII.GetString(fromNetwork));
bluetoothStream.Write(fromNetwork, 0, 1024);
bluetoothStream.Flush();
while (bluetoothStream.CanRead)
{
Array.Clear(fromBluetooth, 0, 1024);
bluetoothStream.Read(fromBluetooth, 0, 1024);
Console.WriteLine(Encoding.ASCII.GetString(fromNetwork));
networkStream.Write(fromBluetooth, 0, 1024);
networkStream.Flush();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
this.HandleThread();
}
private bool findDevice(out BluetoothDeviceInfo device)
{
peers = client.DiscoverDevicesInRange();
device = Array.Find(peers, element => element.DeviceName == match);
foreach (BluetoothDeviceInfo btdi in peers)
{
Console.WriteLine(btdi.DeviceName);
}
if (device == null)
{
Console.WriteLine(Name +": Not Found");
return false;
}
else
{
Console.WriteLine(Name +": Found");
return true;
}
}
}
}
最佳答案
我正在使用套接字来与蓝牙设备通信。断开连接时释放任何资源非常重要。
为了找到您的 COM 端口,您可以使用 this link
您的流位于此处:
System.Net.Sockets.NetworkStream stream = bthClient.GetStream();
有关如何连接和查找您的设备的示例。
private InTheHand.Net.Sockets.BluetoothClient _BTClient = null;
private InTheHand.Net.Sockets.BluetoothDeviceInfo[] _clientDevices;
/// <summary>
/// Thread function to discover devices
/// </summary>
private void DiscoverBluetoothThread()
{
try
{
_BTClient = new InTheHand.Net.Sockets.BluetoothClient();
_clientDevices = _BTClient.DiscoverDevices(999, _authenticated, _remembered, _unknown);
_BTClient.Dispose();
_BTClient = null;
}
catch (Exception) { }
}
Private void Connect(InTheHand.Net.Sockets.BluetoothDeviceInfo info)
{
string addressN = info.DeviceAddress.ToString("N"); //Format Example: "00066606E014"
string addressC = info.DeviceAddress.ToString("C"); //Format Example: "00:06:66:06:E0:14"
string addressP = info.DeviceAddress.ToString("P"); //Format Example: "00.06.66.06.E0.14"
string addressD = info.DeviceAddress.ToString(); //Format Example: "00066606E014"
string serialPort = FindBluetoothPortName(addressN);
//https://stackoverflow.com/questions/26439091/how-to-get-bluetooth-device-com-serial-port-in-winform-c/27919129#27919129
if (string.IsNullOrEmpty(serialPort) == false && serialPort.Trim().Length > "COM".Length)
bool installed = InstallBluetoothDevice(addressC, passKey, autoConnect);
}
public bool InstallBluetoothDevice(string deviceMACAddress, string passKey, bool connect)
{
string strDevicePassKey = passKey;
string BTMac = deviceMACAddress;
InTheHand.Net.BluetoothAddress BTAddress;
InTheHand.Net.Sockets.BluetoothClient BTClient = new InTheHand.Net.Sockets.BluetoothClient();
InTheHand.Net.BluetoothEndPoint BTEndPoint;
InTheHand.Net.Bluetooth.BluetoothRadio BTRadio;
BTRadio = InTheHand.Net.Bluetooth.BluetoothRadio.PrimaryRadio;
BTRadio.Mode = RadioMode.Connectable;
Guid spguid = BluetoothService.SerialPort;
BTAddress = InTheHand.Net.BluetoothAddress.Parse(BTMac);
BTEndPoint = new InTheHand.Net.BluetoothEndPoint(BTAddress, spguid);
try
{
BluetoothSecurity.PairRequest(BTAddress, strDevicePassKey);
//Application.DoEvents();
BTClient = new InTheHand.Net.Sockets.BluetoothClient();
if (connect)
{
BTClient.Connect(BTEndPoint);
BTEndPoint = new InTheHand.Net.BluetoothEndPoint(BTAddress, spguid);
_connectedDevices.Add(BTAddress, BTClient);
return BTClient.Connected;
}
return true;
}
catch (Exception ex)
{
return false;
}
}
关于C# 32feet.Net : Handling two bluetooth connections in seperate threads, 给出 SocketException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25379705/
我们在 Android 网络请求方面遇到问题,更确切地说是随机接收 SocketException: java.net.SocketException: socket is closed at
我有一个大型 Java 应用程序(用于生成某种类型的报告),其中下面的类用于创建数据源。 import org.apache.log4j.Logger; import org.springfram
.htaccess 中的过滤和 SocketException 之间有联系吗?假设在 .htaccess 中对 host.are.everywhere.in.the.net 进行了拒绝如果我从那个被拒
我正在创建一个示例应用程序 (java),它收集信息并将该信息发送到 .net 中内置的 Web 服务。通常它工作正常。两个平台都在完美沟通。 但经过一段时间后,我收到了 (java.net.Sock
java.net.SocketException: Connection reset 之间有什么区别?和 java.net.SocketException: Broken Pipe? 我想弄清楚这两个
我正在使用strapi.io 开源 Node.js headless CMS 这是我的注册页面代码 无效_registerUser()异步{ http.Response response =
这个问题在这里已经有了答案: Official reasons for "Software caused connection abort: socket write error" (14 个答案)
我看过别处,每个网站都告诉我这实际上是互联网连接错误......但我知道这不可能是正确的。 我正在使用 Flutter (dart) 为 iOS(在 Mac 上)编程。我在 iOS 模拟器和实际的 i
我正在尝试使用我的智能手机(不是模拟器)连接到我的带有 SignalR 后端的 Aspnet Core。我将 Cors 添加到 Startup.cs: public void ConfigureSer
如何阻止 SocketException 的发生? 我正在尝试将序列化对象从客户端简单传输到本地计算机上的服务器。 我已经能够使用以下代码的细微变化来发送字符串,但是当我尝试发送对象时 Custome
我正在尝试 Dart,我已经为此苦苦挣扎了很久。来电: runServer() { HttpServer.bind(InternetAddress.ANY_IP_V4, 8080) .then
我开发了一个小型 GUI 应用程序,用于从远程服务器下载日志文件。如果我从 Netbeans IDE 7.2 中启动该应用程序,则它可以正常工作(没有连接问题) 但是如果我将其作为独立的 jar 文件
我有客户端类和服务器类,但是当我运行两个主要方法时,什么都不会发生,当我停止运行时,会发生此异常。为什么??请帮助我,我该如何解决它??? 我的客户端类: public class Client {
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.
我创建了一个接受 TCP 连接的服务器。连接到套接字后,它循环从输入流读取数据。 步骤: 我启动了我的服务器。 启动客户端。 现在我要关闭客户端。 然后服务器给我 SocketException Co
我有一个 java 应用程序在 centos 6.3 和 tomcat 7 作为应用程序容器上运行,目前遇到一个错误:java.io.socketexception 达到数据报套接字的最大数量 我们使
我正在使用 C# UdpClient 类连接到 UDP 网络。有一个 UdpClient 对象,绑定(bind)到一个固定的本地端口,但不绑定(bind)到任何远程端点,因为它需要能够向/从多个不同的
我想知道是否有一种方法可以避免在我无法连接时获取 SocketException 而不是使用 try/catch 捕获 SocketException。 我有这段代码可以检查服务器是否可用: publ
我决定看看网络消息传递等,我的第一个调用端口是 UDP。 我遇到的问题是当我尝试发送消息时。我正在尝试在特定端口上访问 IP,但应用程序错误并出现错误 “SocketException 一个现有的连接
我有一个 Java 服务器/客户端应用程序,它使用 while 循环允许客户端输入直到断开连接。这是在扩展 Thread 并使用 run() 方法的 ClientHandler 类对象中完成的,因此每
我是一名优秀的程序员,十分优秀!