• 0216 488 01 91
  • destek@sonsuzbilgi.com.tr

Danışmanlık Web Sitesi

Onlarca Danışmanlık Web Sitesinden Biri Mutlaka Size Göre!

*256 Bit SSL Sertifikası * Full Mobil Uyumlu * Full SEO Uyumlu
İsterseniz Mobil Uygulama Seçeneğiyle


C# Socket İstemci ve Sunucu Örnekleri

Adı : C# Socket İstemci ve Sunucu Örnekleri

Bu yazıda, C# kullanarak socket istemcisi ve sunucusu nasıl oluşturulur hakkında ayrıntılı bir rehber sunacağız. Bu yazıda yapacaklarımız;

- C# kullanarak socket nedir ve nasıl çalışır.
- Socket istemcisi ve sunucusu için C# kodlarını oluşturma.
- İstemci ve sunucu örneklerini yapma.
- Sık Sorulan Soruları yanıtlama.

C# kullanarak socket nedir ve nasıl çalışır?

Connection-based communication için socket, İşletim sistemi tarafından sunulan bir API dir. Socket sağlayıcılar, uygulamaların diğer uygulamalarla iletişim kurmasına izin verir. Socket, uygulamanın bir ağ üzerinden bir bağlantı kurmasına, mesajlar göndermesine ve almasına izin verir.

Sockets, TCP / IP protokolünün bir parçasıdır ve ağ üzerinden iletişim kurmak için kullanılır.

Socketistemi, iletişim kurulacak iki cihaz arasında kurmaya yarar. Bir tarafta sunucu ve diğer tarafta istemci bilgisayar olmalıdır. Sunucu, belirli bir IP adresine ve bir bağlantı noktasına bağlanarak, istemciden gelen bağlantıları dinler. İstemci, sunucunun IP adresine ve bağlantı noktasına bağlanarak, sunucunun sağladığı hizmetlere erişebilir.

Socket istemcisi ve sunucusu için C# kodlarını oluşturma

Socket istemcisi ve sunucusu nasıl oluşturulacağına bakmadan önce, C# diliyle ne tür bir soket istemci veya sunucusuna ihtiyacımız olduğuna karar vermemiz gerekir. İşlem, bağlantı noktası numarası ve diğer ayarlar gibi birçok faktöre bağlıdır.

Aşağıdaki örneklerden socket istemcisi ve sunucusu oluşturacağız;

- TCP Sunucusu ve İstemcisi
- UDP Sunucusu ve İstemcisi

TCP Server ve İstemci

TCP Client
İlk olarak, client.ip ile belirtilen IP adresine ve client.port belirtilen bağlantı noktasına bir istek gönderen basit bir TCP istemci örneği verelim.

```
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

class TCPClient
{
public static void Main(string[] args)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 13000;
TcpClient client = new TcpClient(\"127.0.0.1\", port);

// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(\"Hello TCP Server, I'm TCP Client\");

// Get a client stream for reading and writing.
// Stream stream = client.GetStream();

NetworkStream stream = client.GetStream();

// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);

Console.WriteLine(\"Sent: {0}\", data);

// Receive the TcpServer.response.

// Buffer to store the response bytes.
data = new Byte[256];

// String to store the response ASCII representation.
String responseData = String.Empty;

// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine(\"Received: {0}\", responseData);

// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine(\"ArgumentNullException: {0}\", e);
}
catch (SocketException e)
{
Console.WriteLine(\"SocketException: {0}\", e);
}
Console.WriteLine(\"\
Press Enter to continue...\");
Console.Read();
}
}
```

Yukarıdaki örnek, \"127.0.0.1\" adresindeki bir TCP sunucusuna \"Hello TCP Server, I'm TCP Client\" olarak tanımlanan bir mesaj gönderir ve örneğin cevabını alır.

TCP Server

Ardından, belirli bir yere bağlanarak bir TCP sunucusu örneği verelim.

```
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

class TCPServer
{
public static void Main()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse(\"127.0.0.1\");

// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);

// Start listening for client requests.
server.Start();

// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;

// Enter the listening loop.
while (true)
{
Console.Write(\"Waiting for a connection... \");

// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine(\"Connected!\");

data = null;

// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();

Int32 i;

// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine(\"Received: {0}\", data);

// Process the data sent by the client.
data = data.ToUpper();

byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine(\"Sent: {0}\", data);
}

// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine(\"SocketException: {0}\", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}

Console.WriteLine(\"\
Hit enter to continue...\");
Console.Read();
}
}
```

Yukarıdaki örnek, 127.0.0.1 IP adresindeki 13000 numaralı bağlantı noktasında bir TCP sunucusu başlatır. Sunucu, bir istemci bağlanır bağlanmaz, tanımlanan mesajı büyük harflere dönüştürerek tekrar gönderir.

UDP Sunucusu ve İstemcisi

UDP Sunucusu

UDP sunucusu, gelen UDP bağlantılarını dinleyen ve aldığı verilere yanıt veren bir programdır.

```
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class UDPServer
{
static void Main(string[] args)
{
UdpClient server = new UdpClient(11000);
Console.WriteLine(\"Server started; listening on port 11000...\");

while (true)
{
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
byte[] data = server.Receive(ref sender);

Console.WriteLine(\"Received data from \" + sender.Address + \":\" + sender.Port + \")\");
Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));
}
}
}
```

UDP İstemcisi

Şimdi de, IP adresi ve bağlantı noktası belirtilen UDP sunucusuna bir mesaj gönderen UDP istemci örneği yapıyoruz.

```
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Client
{
class Program
{
static void Main(string[] args)
{
string serverIp = \"127.0.0.1\";
int serverPort = 11000;
UdpClient client = new UdpClient();

try
{
while (true)
{
// Send message to server
Console.Write(\"Enter a message: \");
string messageToSend = Console.ReadLine();
byte[] data = Encoding.ASCII.GetBytes(messageToSend);
IPEndPoint server = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);
client.Send(data, data.Length, server);
}
}
catch (Exception ex)
{
Console.WriteLine(\"Exception: \" + ex.Message);
}
finally
{
client.Close();
}
}
}
}
```

Yukarıdaki örnek, 127.0.0.1 IP adresindeki 11000 numaralı bağlantı noktasına bir mesaj gönderir.


Sık Sorulan Sorular

- Socket Nedir?

Socket bir API'dir ve iletişim için kullanılır. Uygulamanın diğer uygulamalarla iletişim kurmasına izin verir.

- TCP Nedir ve UDP Nedir?

TCP (Transmission Control Protocol) ve UDP (User Datagram Protocol), iletişim kurmak için kullanılan protokollerdir. İki protokol arasındaki ana fark, TCP'nin bağlantı tabanlı olması ve verinin yanıt için beklenerek doğruluğu garanti etmesidir. UDP, verinin doğruluğunu garanti etmez.

- Ağ Üzerinden Sinyal Göndermedeki En Önemli Hata Nedir?

Ağ üzerinden sinyal göndermedeki en önemli hata, paket kaybı olarak bilinir. Paket kaybı, ağ üzerinde veri paketlerinin kaybolmasına neden olan bir durumdur.

- Bir Program Hangi Durumlarda Socket Oluşturur?

Bir program, iki farklı cihaz arasında iletişim kurmak istediğinde socket oluşturur. Bu, iletişim kurmak için kullanılan diğer programın IP adresi ve bağlantı noktası gibi belirli bilgileri içerir.

- Bir Socket Bittiği Zaman Ne Olur?

Bir soket bittiğinde, ağ üzerindeki diğer bağlantılar kesilir ve socket işlemi sona erer. Bu, diğer cihazlarla olan bağlantıların kesilmesine neden olur ve iletişim kurulmaz."

C# Socket İstemci ve Sunucu Örnekleri

Adı : C# Socket İstemci ve Sunucu Örnekleri

Bu yazıda, C# kullanarak socket istemcisi ve sunucusu nasıl oluşturulur hakkında ayrıntılı bir rehber sunacağız. Bu yazıda yapacaklarımız;

- C# kullanarak socket nedir ve nasıl çalışır.
- Socket istemcisi ve sunucusu için C# kodlarını oluşturma.
- İstemci ve sunucu örneklerini yapma.
- Sık Sorulan Soruları yanıtlama.

C# kullanarak socket nedir ve nasıl çalışır?

Connection-based communication için socket, İşletim sistemi tarafından sunulan bir API dir. Socket sağlayıcılar, uygulamaların diğer uygulamalarla iletişim kurmasına izin verir. Socket, uygulamanın bir ağ üzerinden bir bağlantı kurmasına, mesajlar göndermesine ve almasına izin verir.

Sockets, TCP / IP protokolünün bir parçasıdır ve ağ üzerinden iletişim kurmak için kullanılır.

Socketistemi, iletişim kurulacak iki cihaz arasında kurmaya yarar. Bir tarafta sunucu ve diğer tarafta istemci bilgisayar olmalıdır. Sunucu, belirli bir IP adresine ve bir bağlantı noktasına bağlanarak, istemciden gelen bağlantıları dinler. İstemci, sunucunun IP adresine ve bağlantı noktasına bağlanarak, sunucunun sağladığı hizmetlere erişebilir.

Socket istemcisi ve sunucusu için C# kodlarını oluşturma

Socket istemcisi ve sunucusu nasıl oluşturulacağına bakmadan önce, C# diliyle ne tür bir soket istemci veya sunucusuna ihtiyacımız olduğuna karar vermemiz gerekir. İşlem, bağlantı noktası numarası ve diğer ayarlar gibi birçok faktöre bağlıdır.

Aşağıdaki örneklerden socket istemcisi ve sunucusu oluşturacağız;

- TCP Sunucusu ve İstemcisi
- UDP Sunucusu ve İstemcisi

TCP Server ve İstemci

TCP Client
İlk olarak, client.ip ile belirtilen IP adresine ve client.port belirtilen bağlantı noktasına bir istek gönderen basit bir TCP istemci örneği verelim.

```
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

class TCPClient
{
public static void Main(string[] args)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 13000;
TcpClient client = new TcpClient(\"127.0.0.1\", port);

// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(\"Hello TCP Server, I'm TCP Client\");

// Get a client stream for reading and writing.
// Stream stream = client.GetStream();

NetworkStream stream = client.GetStream();

// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);

Console.WriteLine(\"Sent: {0}\", data);

// Receive the TcpServer.response.

// Buffer to store the response bytes.
data = new Byte[256];

// String to store the response ASCII representation.
String responseData = String.Empty;

// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine(\"Received: {0}\", responseData);

// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine(\"ArgumentNullException: {0}\", e);
}
catch (SocketException e)
{
Console.WriteLine(\"SocketException: {0}\", e);
}
Console.WriteLine(\"\
Press Enter to continue...\");
Console.Read();
}
}
```

Yukarıdaki örnek, \"127.0.0.1\" adresindeki bir TCP sunucusuna \"Hello TCP Server, I'm TCP Client\" olarak tanımlanan bir mesaj gönderir ve örneğin cevabını alır.

TCP Server

Ardından, belirli bir yere bağlanarak bir TCP sunucusu örneği verelim.

```
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

class TCPServer
{
public static void Main()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse(\"127.0.0.1\");

// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);

// Start listening for client requests.
server.Start();

// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;

// Enter the listening loop.
while (true)
{
Console.Write(\"Waiting for a connection... \");

// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine(\"Connected!\");

data = null;

// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();

Int32 i;

// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine(\"Received: {0}\", data);

// Process the data sent by the client.
data = data.ToUpper();

byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine(\"Sent: {0}\", data);
}

// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine(\"SocketException: {0}\", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}

Console.WriteLine(\"\
Hit enter to continue...\");
Console.Read();
}
}
```

Yukarıdaki örnek, 127.0.0.1 IP adresindeki 13000 numaralı bağlantı noktasında bir TCP sunucusu başlatır. Sunucu, bir istemci bağlanır bağlanmaz, tanımlanan mesajı büyük harflere dönüştürerek tekrar gönderir.

UDP Sunucusu ve İstemcisi

UDP Sunucusu

UDP sunucusu, gelen UDP bağlantılarını dinleyen ve aldığı verilere yanıt veren bir programdır.

```
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class UDPServer
{
static void Main(string[] args)
{
UdpClient server = new UdpClient(11000);
Console.WriteLine(\"Server started; listening on port 11000...\");

while (true)
{
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
byte[] data = server.Receive(ref sender);

Console.WriteLine(\"Received data from \" + sender.Address + \":\" + sender.Port + \")\");
Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));
}
}
}
```

UDP İstemcisi

Şimdi de, IP adresi ve bağlantı noktası belirtilen UDP sunucusuna bir mesaj gönderen UDP istemci örneği yapıyoruz.

```
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Client
{
class Program
{
static void Main(string[] args)
{
string serverIp = \"127.0.0.1\";
int serverPort = 11000;
UdpClient client = new UdpClient();

try
{
while (true)
{
// Send message to server
Console.Write(\"Enter a message: \");
string messageToSend = Console.ReadLine();
byte[] data = Encoding.ASCII.GetBytes(messageToSend);
IPEndPoint server = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);
client.Send(data, data.Length, server);
}
}
catch (Exception ex)
{
Console.WriteLine(\"Exception: \" + ex.Message);
}
finally
{
client.Close();
}
}
}
}
```

Yukarıdaki örnek, 127.0.0.1 IP adresindeki 11000 numaralı bağlantı noktasına bir mesaj gönderir.


Sık Sorulan Sorular

- Socket Nedir?

Socket bir API'dir ve iletişim için kullanılır. Uygulamanın diğer uygulamalarla iletişim kurmasına izin verir.

- TCP Nedir ve UDP Nedir?

TCP (Transmission Control Protocol) ve UDP (User Datagram Protocol), iletişim kurmak için kullanılan protokollerdir. İki protokol arasındaki ana fark, TCP'nin bağlantı tabanlı olması ve verinin yanıt için beklenerek doğruluğu garanti etmesidir. UDP, verinin doğruluğunu garanti etmez.

- Ağ Üzerinden Sinyal Göndermedeki En Önemli Hata Nedir?

Ağ üzerinden sinyal göndermedeki en önemli hata, paket kaybı olarak bilinir. Paket kaybı, ağ üzerinde veri paketlerinin kaybolmasına neden olan bir durumdur.

- Bir Program Hangi Durumlarda Socket Oluşturur?

Bir program, iki farklı cihaz arasında iletişim kurmak istediğinde socket oluşturur. Bu, iletişim kurmak için kullanılan diğer programın IP adresi ve bağlantı noktası gibi belirli bilgileri içerir.

- Bir Socket Bittiği Zaman Ne Olur?

Bir soket bittiğinde, ağ üzerindeki diğer bağlantılar kesilir ve socket işlemi sona erer. Bu, diğer cihazlarla olan bağlantıların kesilmesine neden olur ve iletişim kurulmaz."


Ankara Plaket İmalatı

Tüm Plaket ihtiyaçlarınız için Buradayız!

Kristal, Ahşap, Bayrak.. Plaket ihtiyaçlarınıza Mükemmel çözümler üretiyoruz.


C# socket programlama istemci sunucu veri iletişimi IP adresi port numarası TCP UDP protokolleri