Untitled
unknown
csharp
2 years ago
2.4 kB
2
Indexable
using System; using System.IO; using System.Text; using InTheHand.Net; using InTheHand.Net.Sockets; using InTheHand.Net.Bluetooth; public class Program { public static void Main(string[] args) { try { Console.WriteLine("Starting Bluetooth communication..."); // Create the Bluetooth client BluetoothClient client = new BluetoothClient(); // Discover devices in range Console.WriteLine("Discovering devices..."); BluetoothDeviceInfo[] devices = client.DiscoverDevicesInRange(); // If no devices were found, terminate the program if (devices.Length == 0) { Console.WriteLine("No devices found. Exiting..."); return; } // Choose the first device BluetoothDeviceInfo device = devices[0]; Console.WriteLine($"Connecting to device: {device.DeviceName}"); // Create the Bluetooth end point BluetoothEndPoint endPoint = new BluetoothEndPoint(device.DeviceAddress, BluetoothService.SerialPort); // Connect to the device client.Connect(endPoint); Console.WriteLine("Connected successfully!"); // Get the stream Stream stream = client.GetStream(); // Your message to send string message = "Hello, Bluetooth!"; byte[] messageBuffer = Encoding.ASCII.GetBytes(message); while (true) { if (stream.CanWrite) { stream.Write(messageBuffer, 0, messageBuffer.Length); Console.WriteLine($"Sent data to Bluetooth: {message}"); } if (stream.CanRead) { byte[] receiveBuffer = new byte[1024]; int bytesRead = stream.Read(receiveBuffer, 0, receiveBuffer.Length); string receivedMessage = Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead); Console.WriteLine($"Received data from Bluetooth: {receivedMessage}"); } } } catch (Exception ex) { Console.WriteLine("An error occurred: " + ex.Message); } } }
Editor is loading...