C # 'de Soket Programlama

Durum
Üzgünüz bu konu cevaplar için kapatılmıştır...
Ya istiklâl ya ölüm
Seçkin Üye
Katılım
7 May 2019
Mesajlar
308
Çözümler
2
Tepki puanı
25
Ödüller
7
7 HİZMET YILI
Bilmeyen veya çözemeyen arkadaşlar için en baştan anlatmak istedim.

C# 'de Soket Programlama nedir ne işe yarar

Bilgisayar ağlarındaki soketler, iki veya daha fazla bilgisayar arasında bağlantı kurmak için kullanılır ve bir bilgisayardan diğerine veri göndermek için kullanılır. Ağdaki her bilgisayara düğüm denir. Soketler, güvenli bir iletişim kanalı oluşturmak için düğümlerin IP adreslerini ve bir ağ protokolünü kullanır ve verileri aktarmak için bu kanalı kullanır.
SocketInCSharp.jpg


Soket istemci ve sunucu iletişimi.

Soket iletişiminde, bir düğüm dinleyici, diğer düğüm istemci olarak işlev görür. Dinleyici düğümü, önceden belirlenmiş bir IP adresinde ve önceden tanımlanmış bir protokolde açılır ve dinlemeye başlar. Sunucuya mesaj göndermek isteyen istemciler aynı IP adresinde ve aynı protokolde mesaj yayınlamaya başlar. Tipik bir soket bağlantısı iletişim kurmak için İletim Kontrol Protokolünü (TCP) kullanır.

Adım 1 - Dinleyici Oluştur.

istemciler aynı IP adresinde ve aynı protokolde mesaj yayınlamaya başlar. Tipik bir soket bağlantısı iletişim kurmak için İletim Kontrol Protokolünü (TCP) kullanır.
İstemci uygulaması, bir sunucu / dinleyici ile bağlantı kuran ve mesaj gönderen uygulamadır. Başka bir .NET Core konsol uygulaması oluşturun veaşağıdaki kodu yazın.

C#:
using System; 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 
 
// Socket Listener acts as a server and listens to the incoming   
// messages on the specified port and protocol. 
public class SocketListener 
{ 
    public static int Main(String[] args) 
    { 
        StartServer(); 
        return 0; 
    } 
 
    
    public static void StartServer() 
    { 
        // Get Host IP Address that is used to establish a connection 
        // In this case, we get one IP address of localhost that is IP : 127.0.0.1 
        // If a host has multiple addresses, you will get a list of addresses 
        IPHostEntry host = Dns.GetHostEntry("localhost"); 
        IPAddress ipAddress = host.AddressList[0]; 
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);   
        
 
        try {   
 
            // Create a Socket that will use Tcp protocol     
            Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 
            // A Socket must be associated with an endpoint using the Bind method 
            listener.Bind(localEndPoint); 
            // Specify how many requests a Socket can listen before it gives Server busy response. 
            // We will listen 10 requests at a time 
            listener.Listen(10); 
 
            Console.WriteLine("Waiting for a connection..."); 
            Socket handler = listener.Accept(); 
 
             // Incoming data from the client.   
             string data = null; 
             byte[] bytes = null; 
 
            while (true) 
            { 
                bytes = new byte[1024]; 
                int bytesRec = handler.Receive(bytes); 
                data += Encoding.ASCII.GetString(bytes, 0, bytesRec); 
                if (data.IndexOf("<EOF>") > -1) 
                { 
                    break; 
                } 
            } 
 
            Console.WriteLine("Text received : {0}", data); 
 
            byte[] msg = Encoding.ASCII.GetBytes(data); 
            handler.Send(msg); 
            handler.Shutdown(SocketShutdown.Both); 
            handler.Close(); 
        } 
        catch (Exception e) 
        { 
            Console.WriteLine(e.ToString()); 
        } 
 
        Console.WriteLine("\n Press any key to continue..."); 
        Console.ReadKey(); 
    }         
}


Listelenen kod, TCP protokolünü ve istemciden alınan mesajları kullanarak yerel ana bilgisayarda bir Soket dinleyicisi oluşturur, bunu konsolda görüntüler. Dinleyici bir seferde 10 istemci isteyebilir ve 11. istek sunucuya meşgul mesajı verir.

Socket-Server.jpg



2. Adım - İstemci Oluştur

İstemci uygulaması, bir sunucu / dinleyici ile bağlantı kuran ve mesaj gönderen uygulamadır. Başka bir .NET Core konsol uygulaması oluşturun ve aşağıdaki kodu yaz
örnek kod, verilen IP ve bağlantı noktasındaki dinleyici ile bir soket bağlantısı oluşturan ve bir ileti gönderen bir istemci uygulaması oluşturur.

C#:
using System; 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 
 
// Client app is the one sending messages to a Server/listener.   
// Both listener and client can send messages back and forth once a   
// communication is established. 
public class SocketClient 
{ 
    public static int Main(String[] args) 
    { 
        StartClient(); 
        return 0; 
    } 
 
 
    public static void StartClient() 
    { 
        byte[] bytes = new byte[1024]; 
 
        try 
        { 
            // Connect to a Remote server 
            // Get Host IP Address that is used to establish a connection 
            // In this case, we get one IP address of localhost that is IP : 127.0.0.1 
            // If a host has multiple addresses, you will get a list of addresses 
            IPHostEntry host = Dns.GetHostEntry("localhost"); 
            IPAddress ipAddress = host.AddressList[0]; 
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000); 
 
            // Create a TCP/IP  socket.   
            Socket sender = new Socket(ipAddress.AddressFamily, 
                SocketType.Stream, ProtocolType.Tcp); 
 
            // Connect the socket to the remote endpoint. Catch any errors.   
            try 
            { 
                // Connect to Remote EndPoint 
                sender.Connect(remoteEP); 
 
                Console.WriteLine("Socket connected to {0}", 
                    sender.RemoteEndPoint.ToString()); 
 
                // Encode the data string into a byte array.   
                byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>"); 
 
                // Send the data through the socket.   
                int bytesSent = sender.Send(msg); 
 
                // Receive the response from the remote device.   
                int bytesRec = sender.Receive(bytes); 
                Console.WriteLine("Echoed test = {0}", 
                    Encoding.ASCII.GetString(bytes, 0, bytesRec)); 
 
                // Release the socket.   
                sender.Shutdown(SocketShutdown.Both); 
                sender.Close(); 
 
            } 
            catch (ArgumentNullException ane) 
            { 
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); 
            } 
            catch (SocketException se) 
            { 
                Console.WriteLine("SocketException : {0}", se.ToString()); 
            } 
            catch (Exception e) 
            { 
                Console.WriteLine("Unexpected exception : {0}", e.ToString()); 
            } 
 
        } 
        catch (Exception e) 
        { 
            Console.WriteLine(e.ToString()); 
        } 
    } 
}


Adım 3 - Test Et ve Çalıştır

Şimdi her iki projeyi de oluştur ve her iki uygulamayı da komut satırından çalıştır. İstemci tarafından gönderilen mesajın dinleyici tarafından okunduğunu ve görüntülendiğini göreceksin. İstemci çalıştığında, iletinin sunucuya gönderildiğini göreceksin.

SocketInCSharp.jpg
 
Son düzenleme:
Bu gözler neler gördü neler
Süper Üye
Katılım
7 Eyl 2015
Mesajlar
731
Çözümler
39
Tepki puanı
327
Ödüller
9
Yaş
32
10 HİZMET YILI
Ellerine sağlık geniş bir anlatım olmuş, bu konuda araştırma yapan çoğu kişinin işine yarayabilir.
 
Seçkin Üye
Katılım
6 Ocak 2017
Mesajlar
413
Çözümler
1
Tepki puanı
84
Ödüller
7
9 HİZMET YILI
güzel güzelde hangi siteden aldıysan ilk önce siteyi türkçeye çevirmişsin kodlarda bozulmuş onları düzelt istersen :thonkie::thinkie::mum:
 
re work
Süper Üye
Katılım
31 Ocak 2016
Mesajlar
952
Çözümler
8
Tepki puanı
458
Ödüller
9
10 HİZMET YILI
php 'de soket programlama yapıyorum fakat c# 'ya yeni başladık bundada işe yarar bilgiler iş görüyor teşekkürler.
 
Onaylı Üye
Katılım
6 Nis 2020
Mesajlar
108
Tepki puanı
13
6 HİZMET YILI
buna benzer bir yöntem ile askerdeyken ana bilgisayara rakam gönderip kontrolleri sağlıyordum diğer bilgisayarlardan
Emeğine sağlık
Post automatically merged:

php 'de soket programlama yapıyorum fakat c# 'ya yeni başladık bundada işe yarar bilgiler iş görüyor teşekkürler.
php de socket nasıl yapıyorsun dostum ? Hatta konu açıp sende anlatabilirsen memnun olurum
Elimde Nodemcu cihaz bulunuyor web üzerinden kontrolünü sağlayacak bir yazılım yapmayı düşünüyorum php blgim var fakat php socket bilmiyorum
 
Seçkin Üye
Katılım
6 Eki 2018
Mesajlar
306
Çözümler
1
Tepki puanı
76
Ödüller
7
7 HİZMET YILI
emeğine sağlık dostum hemen arşivime ekliyorum :)
 
Seçkin Üye
Katılım
22 Mar 2020
Mesajlar
299
Çözümler
1
Tepki puanı
16
Ödüller
4
Yaş
29
6 HİZMET YILI
I am doing socket programming in php, but we just started c #.
 
Durum
Üzgünüz bu konu cevaplar için kapatılmıştır...
Üst