SoFunction
Updated on 2025-03-07

Detailed explanation of Socket communication usage examples in C#

This article describes the usage of Socket communication in C#. Share it for your reference. The details are as follows:

1. UDP method:

Server side code:

static void Main(string[] args)
{
  int recv;
  byte[] data = new byte[1024];
  IPEndPoint ipep = new IPEndPoint(, 9050);//Define a network endpoint  Socket newsock = new Socket(, , );//Define a Socket  (ipep);//Socket is associated with an endpoint on the local  ("Waiting for a client..");
  IPEndPoint sender = new IPEndPoint(, 0);//Define the address of the computer to be sent  EndPoint Remote = (EndPoint)(sender);//
  recv = (data, ref Remote);// Accept data  ("Message received from{0}:", ());
  ((data, 0, recv));
  string welcome = "Welcome to my test server!";
  data = (welcome);
  (data, , , Remote);
  while (true)
  {
    data = new byte[1024];
    recv = (data, ref Remote);
    ((data, 0, recv));
    (data, recv, , Remote);
  }
}

Client code:

void MainInfo()
{
  byte[] data = new byte[1024];//Define an array to use as a buffer for data  string input, stringData;
  IPEndPoint ipep = new IPEndPoint(("192.168.1.21"), 9050);
  Socket server = new Socket(, , );
  string welcome = "Hello,are you there?";
  data = (welcome);
  (data, , , ipep);//Send data to the specified endpoint  IPEndPoint sender = new IPEndPoint(, 0);
  EndPoint Remote = (EndPoint)sender;
  data = new byte[1024];
  int recv = (data, ref Remote);// Accept data from the server  ("Message received from{0}:", ());
  ((data, 0, recv));
  while (true)//Read data  {
    input = ;//Read data from the keyboard    if (input == "text")//End mark    {
      break;
    }
    ((input), Remote);//Send data to the specified endpoint Remote    data = new byte[1024];
    recv = (data, ref Remote);//Receive data from Remote    stringData = (data, 0, recv);
    (stringData);
  }
  ("Stopping client");
  ();
}

2. TCP method:

Server side code:

Socket serverSocket = null;
Thread clientThread = null;
Socket clientSocket = null;
Thread thread = null;
IPAddress ips = null;
PEndPoint ipep = null;
void ServerStart()
{
  ips = (())[0];
  //Create an IPEndPoint instance  ipep = new IPEndPoint(ips, 9050);
  //Create a socket  serverSocket = new Socket(, , );
  (, , true);
  //Bind the created socket with IPEndPoint  (ipep);
  //Set sockets to listen mode  (20);
  while (listenalive)
  {
    try
    {
      //Receive accessed connections on socket      clientSocket = ();
      clientThread = new Thread(new ParameterizedThreadStart(ReceiveData));
      (clientSocket);
    }
    catch (Exception ex)
    {
      WriteErrorLog();
      ();
      serverSocket = null;
    }
  }
}
static void ReceiveData(object obj)
{
  bool keepalive = true;
  Socket s = obj as Socket;
  Byte[] buffer = new Byte[1024];
  //Send information to the client based on the client socket you hear  IPEndPoint clientep = (IPEndPoint);
  ("Client ip:" +  + "Port:" + );
  string welcome = "Connecting to the server successfully";
  buffer = (welcome);
  //Send a "Connecting Server Successfully" message to the client  (buffer, , );
  buffer = new Byte[1024];
  int bufLen = 0;
  string content = ;
  while (true)
  {
    //Receive information sent by the client on the socket    bufLen = 0;
    try
    {
      bufLen = (buffer);
      if (bufLen == 0)
      {
        break;
      }
      content += (buffer, 0, bufLen);
    }
    catch (Exception ex)
    {
      break; ;
    }
  }
  Send(s, content);
  s = null;
  buffer = null;
  clientep = null;
  ();
}

Client code:

void Send(string content)
{
  byte[] data = new byte[1024];
  newclient = new (, , );
  ie = new ((ipadd), port);//The server's IP and port  try
  {
    //Because the client is only used to send information to a specific server, there is no need to bind the IP and port of the machine.  No monitoring is required.    (ie);
  }
  catch ( e)
  {
    (());
    return;
  }
  int recv = (data);
  //Connect successfully on the server  string stringdata = (data, 0, recv);
  if (stringdata == "Connecting to the server successfully")
  {
    ((content));
    ();
    data = new byte[1024];
    recv = (data);
    string result = (data, 0, recv);     
    ();
    ();
    (result);
  }
  else
  {
    ("Connecting to the server failed", "Friendly Tips");
  }
}

I hope this article will be helpful to everyone's C# programming.