Wednesday, April 26, 2023

TCP Socket Programming on Windows in C# Tutorial

Socket Programming Computer Network TCP/IP Tutorial Udemy Course


The Microsoft .NET Framework's (now dotnet) Socket class can program TCP/IP sockets in C# on Windows. The Socket class provides methods and attributes for creating, connecting, sending, and receiving data through TCP/IP sockets.

Discount coupon for my TCP/IP socket programming course:

https://www.udemy.com/course/tcpip-socket-programming-for-coders-using-csharp-net/?couponCode=CHATGPT_TCP_SOCKETS

In C#, here's a simple example of how to create a client that connects to a server over TCP/IP sockets:


using System;

using System.Net;

using System.Net.Sockets;

using System.Text;


class Program {

  static void Main(string[] args) {

    // Establish the remote endpoint for the socket.

    IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");

    IPAddress ipAddress = ipHostInfo.AddressList[0];

    IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, 11000);


    // Create a TCP/IP socket.

    Socket client = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);


    // Connect to the remote endpoint.

    client.Connect(remoteEndPoint);

    Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString());

    // Encode the data string into a byte array.

    byte[] data = Encoding.ASCII.GetBytes("Hello, server!");


    // Send the data through the socket.

    int bytesSent = client.Send(data);


    // Receive the response from the server.

    byte[] buffer = new byte[1024];

    int bytesRec = client.Receive(buffer);

    Console.WriteLine("Server response: {0}", Encoding.ASCII.GetString(buffer, 0, bytesRec));


    // Release the socket.

    client.Shutdown(SocketShutdown.Both);

    client.Close();

  }

}

This example implements a TCP/IP client that connects to a server operating on the same computer (localhost) on port 11000. The client sends the server a "Hello, server!" message and receives a return message.

You can use the following code to construct a TCP/IP server:


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

class Program {
  static void Main(string[] args) {
    // Establish the local endpoint for the socket.
    IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

    // Create a TCP/IP socket.
    Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

    // Bind the socket to the local endpoint and listen for incoming connections.
    listener.Bind(localEndPoint);
    listener.Listen(10);

    Console.WriteLine("Waiting for a connection...");

    // Accept incoming connections and start a new socket to handle communication with the client.
    Socket handler = listener.Accept();
    Console.WriteLine("Connection established with {0}", handler.RemoteEndPoint.ToString());

    // Receive data from the client and send a response.
    byte[] buffer = new byte[1024];
    int bytesRec = handler.Receive(buffer);
    Console.WriteLine("Client message: {0}", Encoding.ASCII.GetString(buffer, 0, bytesRec));

    byte[] response = Encoding.ASCII.GetBytes("Hello, client!");
    handler.Send(response);

    // Release the socket.
    handler.Shutdown(SocketShutdown.Both);
    handler.Close();
  }
}

This example how-to tutorial establishes a TCP/IP server that waits for incoming connections on port 11000. When a client joins, the server accepts the connection and opens a new socket to handle client communication. The server gets a message from the client and responds with its own message.

Please note that these are relatively basic examples. They don't include error handling or advanced capabilities such as asynchronous socket communication. Correct handling of exceptions and problems is critical when working with them in production.

What is a Socket in Computer Networking

A socket is a software endpoint that creates a communication channel between two computers or processes over a network. Think of it like a phone call: To establish communication, you need both a phone number (IP address) and an extension (port number).

Here's what makes up a socket:

  • IP Address: Identifies the computer/device (like "192.168.1.1")
  • Port Number: Identifies the specific process/application (like 80 for HTTP)
  • Protocol: Usually TCP (reliable) or UDP (faster but less reliable)

Types of Sockets:

  1. Stream Sockets (SOCK_STREAM)
    • Uses TCP
    • Reliable, ordered delivery
    • Like a phone conversation
  2. Datagram Sockets (SOCK_DGRAM)[not covered in this tutorial]
    • Uses UDP
    • Faster but unreliable
    • Like sending postcards

Common Network Socket Operations:

  • bind(): Associates the socket with a specific address and port
  • listen(): Waits for incoming connections
  • accept(): Accepts a connection from a client
  • connect(): Establishes a connection to a server
  • send()/recieve(): Sends or receives data
  • close(): Closes the socket

TCP/IP (Transmission Control Protocol/Internet Protocol) and socket programming are fundamental concepts in network communication.

TCP/IP:

  • It's a suite of protocols that powers the internet and most local networks
  • Works in layers:
    • Application Layer (HTTP, FTP, SMTP)
    • Transport Layer (TCP, UDP)
    • Internet Layer (IP)
    • Network Access Layer

Key features of TCP/IP:

  • Connection-oriented (TCP ensures reliable delivery)
  • Packet-based transmission
  • Error checking and recovery
  • Flow control
  • Addressing using IP addresses and ports

Socket Programming: This is the programming interface to create network applications. Think of a socket as a combination of:

  • IP address (where to find the computer)
  • Port number (which program on that computer)
  • Protocol (TCP or UDP

Common Socket Programming Use Cases:

  • Web servers
  • Chat applications
  • Game networking
  • File transfer
  • Remote procedure calls
  • Database connections

3 comments:

  1. การเล่นของค่าย pg slot เว็บ PG เว็บเกมที่มีเกมให้ได้ทดลองเล่นฟรี แล้วก็ยังเป็น PG SLOT รูปแบบใหม่ตอนนี้ของปีแตกง่ายแม้มีทุนน้อยก็เล่นได้

    ReplyDelete

Feel free to talk back...