program network de bind ederek ortamda kendi cihazı varmı diye arıyor varsa bağlanıyor
kodları aşağıda veriyorum
listbox, button ve form var
buttonun click i (bağlanma için burası kullanılıyor)
Kod: Tümünü seç
private void connectB_Click(object sender, EventArgs e)
{
deviceLB.Items.Clear();
m_remoteEP.Address = IPAddress.Broadcast;
foreach (UdpClient client in m_udpClients)
client.Send(Encoding.ASCII.GetBytes("PING"), 4, m_remoteEP);
}
device diye bir sınıf var ayrı bir dosya
Kod: Tümünü seç
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
namespace zamanmak
{
public class Device
{
private string m_mac;
private IPEndPoint m_ep;
public Device(string mac, IPEndPoint ep)
{
m_mac = mac;
m_ep = new IPEndPoint(ep.Address, ep.Port);
}
public IPEndPoint EP
{
get
{
return m_ep;
}
}
public string MAC
{
get
{
return m_mac;
}
}
public override string ToString()
{
return MAC + "=>" + EP;
}
public override bool Equals(object obj)
{
if (obj is Device)
{
Device d = (Device)obj;
return d.EP.Equals(m_ep) && d.MAC == m_mac;
}
return false;
}
}
}
bağlantı için kullanılan diğer sınıflar
Kod: Tümünü seç
/*
* Açılacak UDP Socketleri
*
* UDP sockets which will create soon.
*/
private List<UdpClient> m_udpClients = new List<UdpClient>();
/*
* Hedef IP adresi ve portu.
*
* Destination IP address and port.
*/
private IPEndPoint m_remoteEP = new IPEndPoint(IPAddress.Broadcast, 3802);
public void ReceiveCallback(IAsyncResult ar)
{
/*
* Thread'ler arası haberleşme problemini önlemek için.
*
* To avoid cross-thread problems.
*/
if (this.InvokeRequired)
{
this.BeginInvoke(new AsyncCallback(ReceiveCallback), new object[] { ar });
return;
}
/*
* Callback'in çağrılmasına sebep olan socketi alalım.
*
* This is the socket which triggered the callback.
*/
UdpClient client = (UdpClient)ar.AsyncState;
byte[] data = client.EndReceive(ar, ref m_remoteEP);
/*
* 6-byte'lık MAC adres bilgisi bekliyoruz.
*
* We're expecting a 6-byte message which contains MAC address of the device.
*/
if (data.Length != 6)
{
client.BeginReceive(new AsyncCallback(ReceiveCallback), client);
return;
}
String str = String.Empty;
for (int i = 0; i < data.Length; i++)
str += Convert.ToString(data[i], 16).PadLeft(2, '0') + ":";
/*
* Bulunan cihaz için nesne yarat.
*
* Create an Device instance for the found device
*/
Device dev = new Device(str, m_remoteEP);
if (!deviceLB.Items.Contains(dev))
deviceLB.Items.Add(dev);
client.BeginReceive(new AsyncCallback(ReceiveCallback), client);
}