Wednesday, April 26, 2023

TCP Socket Programming on Windows in C#

The.NET Framework's 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 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.

It should be noted that these are relatively basic examples that do not include error handling or advanced capabilities such as asynchronous socket communication. When working with exceptions and problems, it is critical to handle them correctly.

3 comments:

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

    ReplyDelete

Feel free to talk back...