C Socket Implementation Simple Console Case

  • 2021-12-12 09:27:50
  • OfStack

1. Server side

1. Instantiate and set the socket instance object

a. Create an ip address and port

b. Bind listening address

c. Set the number of simultaneous accesses allowed under 1

2. Listen for connections

a. Execute by starting a new thread so that the main thread does not feign animation (start the thread with arguments of type object)

b. Loop to wait for connection and return 1 socket instance responsible for communication

c. The IP address of the connected customer service can be obtained from the returned socket instance

3. Receive messages from customer service

a. Start 1 new thread execution in listener method

b. Use loop to get the sent message. Calling the method to get the message needs to pass a byte variable parameter as a container. The return value of the method is int, which indicates the number of valid bytes obtained

c. If the number of valid bytes is 0, jump out of the loop

d. Return message to customer service after receiving message

4. Server-side code for the console program


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

namespace ServerSocket
{
 class Program
 {
  static void Main(string[] args)
  {
   Console.WriteLine("Hello World!");
   Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
   IPAddress ip = IPAddress.Any;
   IPEndPoint point = new IPEndPoint(ip, 2333);
   //socket Bind listening address 
   serverSocket.Bind(point);
   Console.WriteLine("Listen Success");
   // Set the number of simultaneous connections 
   serverSocket.Listen(10);

   // Using threads to perform listening in the background , Or the program will fake death 
   Thread thread = new Thread(Listen);
   thread.IsBackground = true;
   thread.Start(serverSocket);

   Console.Read();
  }

  /// <summary>
  ///  Listen for a connection 
  /// </summary>
  /// <param name="o"></param>
  static void Listen(object o)
  {
   var serverSocket = o as Socket;
   while (true)
   {
    // Wait for the connection and create 1 A person in charge of communication socket
    var send = serverSocket.Accept();
    // Gets the linked IP Address 
    var sendIpoint = send.RemoteEndPoint.ToString();
    Console.WriteLine($"{sendIpoint}Connection");
    // Open 1 New threads receive messages without stopping 
    Thread thread = new Thread(Recive);
    thread.IsBackground = true;
    thread.Start(send);
   }
  }

  /// <summary>
  ///  Receive a message 
  /// </summary>
  /// <param name="o"></param>
  static void Recive(object o)
  {
   var send = o as Socket;
   while (true)
   {
    // Gets the sent message container 
    byte[] buffer = new byte[1024 * 1024 * 2];
    var effective = send.Receive(buffer);
    // Valid bytes are 0 Skip 
    if (effective == 0)
    {
     break;
    }
    var str = Encoding.UTF8.GetString(buffer,0, effective);
    Console.WriteLine(str);
             var buffers = Encoding.UTF8.GetBytes("Server Return Message");
             send.Send(buffers);

   }
  }
 }
}

2. Client

1. Instantiate and connect socket instance objects

a. Create an ip address and port (the server's IP and port)

b. Link to server side

2. Receive messages from the server

a. Start 1 new thread execution

b. Use loop to get the sent message. Calling the method to get the message needs to pass a byte variable parameter as a container. The return value of the method is int, which indicates the number of valid bytes obtained

c. If the number of valid bytes is 0, jump out of the loop

3. Send a message to the server

a. Call the send () method of the socket object to send directly

4. Console program client code


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

namespace SocketClient
{
 class Program
 {
  static void Main(string[] args)
  {
   Console.WriteLine("Hello World!");
   // Create an instance 
   Socket socketClient = new Socket(SocketType.Stream, ProtocolType.Tcp);
   IPAddress ip = IPAddress.Parse("192.168.0.111");
   IPEndPoint point = new IPEndPoint(ip, 2333);
   // Make a connection 
   socketClient.Connect(point);
   
   // Receive messages sent by the server without stopping 
   Thread thread = new Thread(Recive);
   thread.IsBackground = true;
   thread.Start(socketClient);

   // Keep sending data to the server 
   int i = 0;
   while (true)
   {
    i++;
    var buffter = Encoding.UTF8.GetBytes($"Test Send Message:{i}");
    var temp = socketClient.Send(buffter);
    Thread.Sleep(1000);
   }
   
  }


  /// <summary>
  ///  Receive a message 
  /// </summary>
  /// <param name="o"></param>
  static void Recive(object o)
  {
   var send = o as Socket;
   while (true)
   {
    // Get the sent message 
    byte[] buffer = new byte[1024 * 1024 * 2];
    var effective = send.Receive(buffer);
    if (effective == 0)
    {
     break;
    }
    var str = Encoding.UTF8.GetString(buffer, 0, effective);
    Console.WriteLine(str);
   }
  }
 }
}

Related articles: