66. Bluetooth ulanishi orqali ma'lumotlarni yuborish va qabul qilish uchun ma'lumotlar oqimidan foydalanadigan C# dasturini yarating.
Javob:
using System.IO;
using System.Net.Sockets;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
namespace BluetoothApplication
{
class Program
{
static void Main(string[] args)
{
BluetoothClient bluetoothClient = new BluetoothClient();
BluetoothDeviceInfo[] devices = bluetoothClient.DiscoverDevices();
Console.WriteLine("Devices:");
for (int i = 0; i < devices.Length; i++)
{
Console.WriteLine(devices[i].DeviceName);
}
Console.Write("Enter device name: ");
string deviceName = Console.ReadLine();
BluetoothDeviceInfo device = null;
for (int i = 0; i < devices.Length; i++)
{
if (devices[i].DeviceName == deviceName)
{
device = devices[i];
break;
}
}
if (device == null)
{
Console.WriteLine("Device not found!");
return;
}
BluetoothAddress address = device.DeviceAddress;
Guid serviceClass = BluetoothService.SerialPort;
BluetoothEndPoint endPoint = new BluetoothEndPoint(address, serviceClass);
BluetoothClient client = new BluetoothClient();
try
{
client.Connect(endPoint);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
Stream stream = client.GetStream();
while (true)
{
Console.Write("Enter message: ");
string message = Console.ReadLine();
if (message == "exit")
{
break;
}
byte[] buffer = System.Text.Encoding.ASCII.GetBytes(message);
stream.Write(buffer, 0, buffer.Length);
buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string response = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Response: " + response);
}
stream.Close();
client.Close();
}
}
}
Do'stlaringiz bilan baham: |