Location>code7788 >text

NET TCP, UDP, Socket, WebSocket

Popularity:415 ℃/2024-07-25 11:16:55

NET application development will definitely use network communication, and inter-process communication is a more frequent scenario for client-side development.

The main methods of inter-process communication are named pipes, message queues, shared memory, socket communication, and personally the most used are Sokcet related.

And there are many ways to use Socket, Socket, WebSocket, TcpClient, UdpClient, is not a lot?What is the relationship between HttpClient and TcpClient, WebSocket? Here we are introduced to these communications and the use of these methods

Socket

No, Socket is a programming interface between the transport layer and the application layer for network communication.Socket can be based on a variety of protocols such as TCP, UDP protocol to realize the process of communication, TCP / UDP is the transmission communication protocols

Socket sits between the transport layer and the application layer, and the interface is under the namespace. The following is a DEMO of Socket communicating over TCP:

    //Creating a Socket Instance
    Socket clientSocket = new Socket(, , );
    
    //Connecting to the server
    (new IPEndPoint(("127.0.0.1"), 8000));
    
    //Send data
    string message = "Hello, Server!";
    byte[] data = (message);
    (data);
    
    //receive data
    byte[] buffer = new byte[1024];
    int bytesRead = (buffer);
    ((buffer, 0, bytesRead));
    
    ();

TcpClient/UdpClient

TCP/UDP are both transport-layer communication protocols, so the use of sockets is also a transport-layer communication operation.

TCP is connection-oriented and provides reliable, sequential transmission of data streams. It is used for one-to-one communication, i.e. a TCP connection can have only one sender and one receiver. So it is suitable for scenarios that require data integrity and reliable transmission

UDP, on the other hand, is connectionless, does not require the establishment and maintenance of the connection state, does not provide an acknowledgement mechanism, and does not retransmit lost datagrams, but also therefore the transmission of real-time is high, suitable for low-latency, small data volume, broadcasting scenarios

Build higher level abstract network programming based on Socket abstract programming interface, TCP, UDPTcpClient、UdpClientThey are used to simplify common tasks in TCP network programming.

TcpClient cap (a poem)UdpClient NET is a class that facilitates the management of TCP and UDP network communication, the following is the corresponding demo

Tcp server:

 1 using System;
 2 using ;
 3 using ;
 4 using ;
 5 
 6 class TcpServerExample
 7 {
 8     public static void Main()
 9     {
10         TcpListener listener = new TcpListener(“127.0.0.1", 8000);
11         ();
12         ("Server is listening on port 8000...");
13 
14         TcpClient client = ();
15         NetworkStream stream = ();
16         
17         byte[] data = new byte[1024];
18         int bytesRead = (data, 0, );
19         ("Received: " + (data, 0, bytesRead));
20 
21         byte[] response = ("Hello, Client!");
22         (response, 0, );
23 
24         ();
25         ();
26         ();
27     }
28 }

TCP client:

 1 using System;
 2 using ;
 3 using ;
 4 
 5 class TcpClientExample
 6 {
 7     public static void Main()
 8     {
 9         TcpClient client = new TcpClient("127.0.0.1", 8000);
10         NetworkStream stream = ();
11 
12         byte[] message = ("Hello, Server!");
13         (message, 0, );
14 
15         byte[] data = new byte[1024];
16         int bytesRead = (data, 0, );
17         ("Received: " + (data, 0, bytesRead));
18 
19         ();
20         ();
21     }
22 }

Udp server:

 1 using System;
 2 using ;
 3 using ;
 4 using ;
 5 
 6 class UdpServerExample
 7 {
 8     public static void Main()
 9     {
10         UdpClient udpServer = new UdpClient(8000);
11         IPEndPoint remoteEP = new IPEndPoint(”127.0.0.1“, 0);
12 
13         ("Server is listening on port 8000...");
14 
15         byte[] data = (ref remoteEP);
16         ("Received: " + (data));
17 
18         byte[] response = ("Hello, Client!");
19         (response, , remoteEP);
20 
21         ();
22     }
23 }

Udp Client:

 1 using System;
 2 using ;
 3 using ;
 4 using ;
 5 
 6 class UdpClientExample
 7 {
 8     public static void Main()
 9     {
10         UdpClient udpClient = new UdpClient();
11         IPEndPoint remoteEP = new IPEndPoint(”127.0.0.1", 8000);
12 
13         byte[] message = ("Hello, Server!");
14         (message, , remoteEP);
15 
16         byte[] data = (ref remoteEP);
17         ("Received: " + (data));
18 
19         ();
20     }
21 }

The above is the basic network communication DEMO, TcpClient for connection-based, reliable TCP communication, applicable to the need for data integrity and reliable transmission of the scene. Udp for no connection, no guarantee of transmission of UDP communication, applicable to the real-time requirements of high, allowing a small amount of data loss scenarios (such as video streaming). Conference scenarios screen transfer software is suitable for this protocol, screen transfer sender fixed frame rate has been pushing, the network lost a few frames is not a big problem, the important thing is that the delay is much lower.

TcpClient, UdpClient are communication classes located in the transport layer, which implement communication functions based on TCP and UDP protocols, respectively.

HttpClient

After talking about the transport layer of the network communication class, we should talk about the application layer of the HttpClient, which is dedicated to the HTTP protocol communication

Http and TCP/UDP are network communication protocols , TCP, UDP is located in the transport layer , HTTP passes to the application layer , and HTTP is based on TCP connection-oriented . HttpClient is the Http protocol communication class , provides encapsulated , high-level HTTP functionality ( such as initiating the GET, POST request, processing the response , etc.).

HttpClient can be used for Web interface calls , my side of the Windows application of the WebApi base component library is to use HttpClient implementation .

HttpClient class, under the namespaceHttpClientThe internal implementation is based on theSocketThe. In other words.HttpClientThe underlying Socket interface is used to establish connections and transfer data, but it hides these details and provides a cleaner API for developers.

The following is based on my implementation of HttpClient Web services all kinds of operations entry code, you can simply browse the next:

 1         /// <summary>
 2         /// Requesting/pushing data
 3         /// </summary>
 4         /// <typeparam name="TResponse"></typeparam>
 5         /// <param name="request"></param>
 6         /// <returns></returns>
 7         public async Task<TResponse> RequestAsync<TResponse>(HttpRequest request) where TResponse : HttpResponse, new()
 8         {
 9             var requestUrl = ();
10             try
11             {
12                 using var client = CreateHttpClient(request);
13                 var requestMethod = ();
14                 switch (requestMethod)
15                 {
16                     case :
17                         {
18                             using var response = await (requestUrl);
19                             return await <TResponse>();
20                         }
21                     case :
22                         {
23                             using var httpContent = ();
24                             using var response = await (requestUrl, httpContent);
25                             return await <TResponse>();
26                         }
27                     case :
28                         {
29                             using var httpContent = ();
30                             using var response = await (requestUrl, httpContent);
31                             return await <TResponse>();
32                         }
33                     case :
34                         {
35                             using var response = await (requestUrl);
36                             return await <TResponse>();
37                         }
38                     case :
39                         {
40                             using var requestMessage = new HttpRequestMessage(, requestUrl);
41                             using var httpContent = ();
42                              = httpContent;
43                             using var response = await (requestMessage);
44                             return await <TResponse>();
45                         }
46                 }
47                 return new TResponse() { Message = $"Unsupported request types: {requestMethod}" };
48             }
49             catch (ArgumentNullException e)
50             {
51                 return new TResponse() { Code = , Message = , JsonData =  };
52             }
53             catch (TimeoutException e)
54             {
55                 return new TResponse() { Code = , Message = , JsonData =  };
56             }
57             catch (Exception e)
58             {
59                 return new TResponse() { Message = , JsonData =  };
60             }
61         }

HttpClient encapsulated network infrastructure components to call the way, but also relatively simple.

Add the interface request description, parameters and request parameters are uniformly defined in a class file:

 1 /// <summary>
 2 /// Intranet Penetration Registration Interface
 3 /// </summary>
 4 [Request("./user/register",)]
 5 [DataContract]
 6 internal class RegisterFrpRequest : HttpRequest
 7 {
 8     public RegisterFrpRequest(string sn, string appName)
 9     {
10         Sn = sn;
11         SeverNames = new List<RequestServiceName>()
12         {
13             new RequestServiceName(appName,"http")
14         };
15     }
16     [DataMember(Name = "sn")]
17     public string Sn { get; set; }
18 
19     [DataMember(Name = "localServerNames")]
20     public List<RequestServiceName> SeverNames { get; set; }
21 }

Then define the results of the request to return data, the base class HttpResponse within the definition of the basic parameters, the state of Success, the status code Code, return the description of the information Message:

 1 [DataContract]
 2 class RegisterFrpResponse : HttpResponse
 3 {
 4 
 5     [DataMember(Name = "correlationId")]
 6     public string CorrelationId { get; set; }
 7 
 8     [DataMember(Name = "data")]
 9     public FrpRegisterData Data { get; set; }
10 
11     /// <summary>
12     /// success or failure
13     /// </summary>
14     public bool IsSuccess => Success && Code == 200000 && Data != null;
15 }

The business layer can then make clean, efficient calls:

var netClient = new NetHttpClient();
var response = await <RegisterFrpResponse>(new RegisterFrpRequest(sn, appName));

WebSocket

WebSocket is also an application layer communication. Unlike Socket, which can implement both types of protocols TCP/UDP, WebSocket relies only on HTTP/HTTPS connections.

Once the handshake is successful, a two-way data transfer can take place between the client and the server, either transferring byte data or text content.

  • Persistent Connection: WebSocket is a persistent connection and the connection remains open for the duration of the session unless it is actively closed.

  • Full-duplex communication: client and server can send data at any time, communication is no longer one-way. Usingclass to implement WebSocket communication, by reducing the overhead of HTTP requests/responses, lower latency.

(indicates contrast)WebSockettogether withWhat about between HttpClient.Both are used for network communication at the application layer, but their uses and communication protocols are different.

  • HttpClientusing the HTTP protocol.WebSocket The WebSocket protocol is used, which passes the HTTP/HTTPS handshake on the initial connection and then switches to the WebSocket protocol for TCP-based communication. So while both use the HTTP protocol, WebSocket subsequently switches to full-duplex TCP-based communication

  • HttpClientBased on the request/response model, each communication is initiated by the client to the server.WebSocketProvides full-duplex communication where both the client and the server can actively send data.

  • HttpClientMainly used for accessing RESTful APIs, downloading files, or sending HTTP requests.WebSocketIt is mainly used to realize low-latency real-time communication, such as inter-process communication and LAN communication.

 

The inter-process communication used by my team's Windows application is encapsulated based on WebSocketSharp, a full-featured, easy-to-use third-party WebSocket libraryGitHub - sta/websocket-sharp

As for why not just use ClientWebSocket.... NETFramework because the team had not switched to .NET yet.

The basic component of LAN communication used by the latter team is to use ClientWebSocket.

Below is part of the WebSocket communication code that I have encapsulated to send events (broadcasts) and listen to event messages sent from other clients:

 1         /// <summary>
 2         /// send a message
 3         /// </summary>
 4         /// <typeparam name="TInput">Send parameter type</typeparam>
 5         /// <param name="client">Target Client</param>
 6         /// <param name="innerEvent">event name</param>
 7         /// <param name="data">Sending parameters</param>
 8         /// <returns></returns>
 9         public async Task<ClientResponse> SendAsync<TInput>(string client, InnerEventItem innerEvent, TInput data)
10         {
11             var message = new ChannelSendingMessage(client, new ClientEvent(, , true), _sourceClient);
12             <TInput>(data);
13             return await SendMessageAsync(, message);
14         }
15 
16         /// <summary>
17         /// Subscribe to messages
18         /// </summary>
19         /// <param name="client">Target Client</param>
20         /// <param name="innerEvent">Event Name</param>
21         /// <param name="func">commission</param>
22         public ClientSubscribedEvent SubscribeFunc(string client, InnerEventItem innerEvent, Func<ClientResponse, object> func)
23         {
24             var eventName = innerEvent?.EventName;
25             if (string.IsNullOrEmpty(eventName) || func == null)
26             {
27                 throw new ArgumentNullException($"{nameof(eventName)} or {nameof(func)}, arguments cannot be null!");
28             }
29 
30             var subscribedEvent = new ClientSubscribedEvent(client, innerEvent, func);
31             SubscribeEvent(subscribedEvent);
32             return subscribedEvent;
33         }
34 
35         /// <summary>
36         /// Subscribe to messages
37         /// </summary>
38         /// <param name="client">Target Client</param>
39         /// <param name="innerEvent">Event Name</param>
40         /// <param name="func">commission</param>
41         public ClientSubscribedEvent SubscribeFuncTask(string client, InnerEventItem innerEvent, Func<ClientResponse, Task<object>> func)
42         {
43             var eventName = innerEvent?.EventName;
44             if (string.IsNullOrEmpty(eventName) || func == null)
45             {
46                 throw new ArgumentNullException($"{nameof(eventName)} or {nameof(func)}, arguments cannot be null!");
47             }
48 
49             var subscribedEvent = new ClientSubscribedEvent(client, innerEvent, func);
50             SubscribeEvent(subscribedEvent);
51             return subscribedEvent;
52         }

 

Keywords: TCP/UDP, HTTP, Socket, TcpClient/UdpClient, HttpClient, WebSocket