create socket in csharp

To create a socket in C#, you can use the System.Net.Sockets namespace. The following code demonstrates how to create a TCP socket in C#:

main.cs
using System;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        // Create an endpoint to listen on
        IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Any, 5000);

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

        // Bind the socket to the local endpoint
        listener.Bind(localEndpoint);

        // Start listening for incoming connections
        listener.Listen(5);

        Console.WriteLine("Server started. Waiting for connections...");

        while (true)
        {
            // Accept an incoming connection
            Socket client = listener.Accept();

            Console.WriteLine("Client connected: {0}", client.RemoteEndPoint);

            // Handle the connection
            // ...

            // Close the connection
            client.Close();
        }
    }
}
954 chars
38 lines

The code creates a TCP socket that listens on port 5000. When a client connects, it accepts the connection and handles it in the while loop.

Similarly, you can create a UDP socket using the same namespace and classes as with TCP. Just replace ProtocolType.Tcp with ProtocolType.Udp when creating the socket.

gistlibby LogSnag