做.NET應用開發肯定會用到網絡通信,而進程間通信是客戶端開發使用頻率較高的場景。
進程間通信方式主要有命名管道、消息隊列、共享內存、Socket通信,個人使用最多的是Sokcet相關。
而Socket也有很多使用方式,Socket、WebSocket、TcpClient、UdpClient,是不是很多?HttpClient與TcpClient、WebSocket之間有什么關系?這里我們分別介紹下這些通信及使用方式
Socket
Socket是傳輸通信協議么?No,Socket是一種傳輸層和應用層之間、用于實現網絡通信的編程接口。Socket可以使用各種協議如TCP、UDP協議實現進程通信,TCP/UDP才是傳輸通信協議
Socket位于傳輸層與應用層之間,接口在System.Net.Sockets命名空間下。下面是Socket以TCP通信的DEMO:
//創建一個 Socket 實例
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//連接到服務器
clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000));
//發送數據
string message = "Hello, Server!";
byte[] data = Encoding.ASCII.GetBytes(message);
clientSocket.Send(data);
//接收數據
byte[] buffer = new byte[1024];
int bytesRead = clientSocket.Receive(buffer);
Debug.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytesRead));
clientSocket.Close();
TcpClient/UdpClient
TCP/UDP均是位于傳輸層的通信協議,所以Socket的使用也是位于傳輸層的通信操作
TCP是面向連接,提供可靠、順序的數據流傳輸。用于一對一的通信,即一個TCP連接只能有一個發送方和一個接收方。詳細連接方式是,先通過三次握手建立連接、然后傳輸數據,傳輸數據完再通過4次揮手關閉連接。所以適用于需要數據完整性和可靠傳輸的場景
而UDP則是無連接的,不需要建立和維護連接狀態,不提供確認機制,也不重傳丟失的數據報,但也因此傳輸實時性高,適合低延時、數據量小、廣播場景
基于Socket抽象編程接口,TCP、UDP構建更高級別抽象網絡編程TcpClient、UdpClient,它們用于簡化TCP網絡編程中的常見任務
TcpClient、UdpClient是 .NET 提供的用于方便管理TCP和UDP網絡通信的類,下面是對應的Demo
Tcp服務端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class TcpServerExample
{
public static void Main()
{
TcpListener listener = new TcpListener(“127.0.0.1", 8000);
listener.Start();
Console.WriteLine("Server is listening on port 8000...");
TcpClient client = listener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
byte[] data = new byte[1024];
int bytesRead = stream.Read(data, 0, data.Length);
Console.WriteLine("Received: " + Encoding.ASCII.GetString(data, 0, bytesRead));
byte[] response = Encoding.ASCII.GetBytes("Hello, Client!");
stream.Write(response, 0, response.Length);
stream.Close();
client.Close();
listener.Stop();
}
}
TCP客戶端:
using System;
using System.Net.Sockets;
using System.Text;
class TcpClientExample
{
public static void Main()
{
TcpClient client = new TcpClient("127.0.0.1", 8000);
NetworkStream stream = client.GetStream();
byte[] message = Encoding.ASCII.GetBytes("Hello, Server!");
stream.Write(message, 0, message.Length);
byte[] data = new byte[1024];
int bytesRead = stream.Read(data, 0, data.Length);
Debug.WriteLine("Received: " + Encoding.ASCII.GetString(data, 0, bytesRead));
stream.Close();
client.Close();
}
}
Udp服務端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class UdpServerExample
{
public static void Main()
{
UdpClient udpServer = new UdpClient(8000);
IPEndPoint remoteEP = new IPEndPoint(”127.0.0.1“, 0);
Console.WriteLine("Server is listening on port 8000...");
byte[] data = udpServer.Receive(ref remoteEP);
Console.WriteLine("Received: " + Encoding.ASCII.GetString(data));
byte[] response = Encoding.ASCII.GetBytes("Hello, Client!");
udpServer.Send(response, response.Length, remoteEP);
udpServer.Close();
}
}
Udp客戶端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class UdpClientExample
{
public static void Main()
{
UdpClient udpClient = new UdpClient();
IPEndPoint remoteEP = new IPEndPoint(”127.0.0.1", 8000);
byte[] message = Encoding.ASCII.GetBytes("Hello, Server!");
udpClient.Send(message, message.Length, remoteEP);
byte[] data = udpClient.Receive(ref remoteEP);
Console.WriteLine("Received: " + Encoding.ASCII.GetString(data));
udpClient.Close();
}
}
上面是基本的網絡通信DEMO,TcpClient用于基于連接、可靠的TCP通信,適用于需要數據完整性和可靠傳輸的場景。Udp用于無連接、不保證傳輸的UDP通信,適用于對實時性要求高、允許少量數據丟失的場景(如視頻流)。會議場景下的傳屏軟件適合用這個協議,傳屏發送端固定幀率一直推送,網絡丟失幾幀問題不大,重要的是延時低了很多。
TcpClient、UdpClient是位于傳輸層的通信類,分別實現了基于TCP和UDP協議的通信功能。
HttpClient
講完傳輸層的網絡通信類,就要說下應用層的HttpClient,這是專門用于HTTP協議的通信
Http與TCP/UDP均是網絡通信協議,TCP、UDP位于傳輸層,HTTP傳于應用層,而且HTTP是基于TCP面向連接的,它是客戶端單向發起的半雙工協議。HTTP1.1之后引入持久連接,允許一個TCP連接進行多次請求/響應傳輸。HTTP層相比TCP它關注請求、響應的內容
HttpClient是Http協議的通信類,提供了封裝好的、高級的HTTP功能(如發起GET, POST請求,處理響應等)。
HttpClient可以用于Web接口如Restful API的調用,我這邊Windows應用的WebApi基礎組件庫就是用HttpClient實現的。
HttpClient類,在System.Net.Http.HttpClient命名空間下,HttpClient的內部實現是基于Socket的。也就是說,HttpClient底層使用Socket接口來建立連接并傳輸數據,但它隱藏了這些細節,為開發者提供了一個更簡潔的API。
下面是我基于HttpClient實現的Web服務各類操作入口代碼,可以簡單瀏覽下:
/// <summary>
/// 請求/推送數據
/// </summary>
/// <typeparam name="TResponse"></typeparam>
/// <param name="request"></param>
/// <returns></returns>
public async Task<TResponse> RequestAsync<TResponse>(HttpRequest request) where TResponse : HttpResponse, new()
{
var requestUrl = request.GetRequestUrl();
try
{
using var client = CreateHttpClient(request);
var requestMethod = request.GetRequestMethod();
switch (requestMethod)
{
case RequestMethod.Get:
{
using var response = await client.GetAsync(requestUrl);
return await response.GetTResponseAsync<TResponse>();
}
case RequestMethod.Post:
{
using var httpContent = request.GetHttpContent();
using var response = await client.PostAsync(requestUrl, httpContent);
return await response.GetTResponseAsync<TResponse>();
}
case RequestMethod.Put:
{
using var httpContent = request.GetHttpContent();
using var response = await client.PutAsync(requestUrl, httpContent);
return await response.GetTResponseAsync<TResponse>();
}
case RequestMethod.Delete:
{
using var response = await client.DeleteAsync(requestUrl);
return await response.GetTResponseAsync<TResponse>();
}
case RequestMethod.PostForm:
{
using var requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUrl);
using var httpContent = request.GetHttpContent();
requestMessage.Content = httpContent;
using var response = await client.SendAsync(requestMessage);
return await response.GetTResponseAsync<TResponse>();
}
}
return new TResponse() { Message = $"不支持的請求類型:{requestMethod}" };
}
catch (ArgumentNullException e)
{
return new TResponse() { Code = NetErrorCodes.ParameterError, Message = e.Message, JsonData = e.StackTrace };
}
catch (TimeoutException e)
{
return new TResponse() { Code = NetErrorCodes.TimeOut, Message = e.Message, JsonData = e.StackTrace };
}
catch (Exception e)
{
return new TResponse() { Message = e.Message, JsonData = e.StackTrace };
}
}
HttpClient封裝后的網絡基礎組件調用方式,也比較簡單。
添加接口請求說明,參數及請求參數均統一在一個類文件里定義好:
/// <summary>
/// 內網穿透注冊接口
/// </summary>
[Request("http://frp.supporter.ws.h3c.com/user/register",RequestMethod.Post)]
[DataContract]
internal class RegisterFrpRequest : HttpRequest
{
public RegisterFrpRequest(string sn, string appName)
{
Sn = sn;
SeverNames = new List<RequestServiceName>()
{
new RequestServiceName(appName,"http")
};
}
[DataMember(Name = "sn")]
public string Sn { get; set; }
[DataMember(Name = "localServerNames")]
public List<RequestServiceName> SeverNames { get; set; }
}
再定義請求結果返回數據,基類HttpResponse內有定義基本參數,狀態Success、狀態碼Code、返回描述信息Message:
[DataContract]
class RegisterFrpResponse : HttpResponse
{
[DataMember(Name = "correlationId")]
public string CorrelationId { get; set; }
[DataMember(Name = "data")]
public FrpRegisterData Data { get; set; }
/// <summary>
/// 是否成功
/// </summary>
public bool IsSuccess => Success && Code == 200000 && Data != null;
}
然后,業務層可以進行簡潔、高效率的調用:
var netClient = new NetHttpClient();
var response = await netClient.RequestAsync<RegisterFrpResponse>(new RegisterFrpRequest(sn, appName));
如果僅僅只是Data數據,可以只定義數據類型,然后使用泛型HttpResponse作為返回數據。
var response1 = await netClient.RequestAsync<HttpResponse<VersionInfo>>(new AppVersionRequest(appId));
WebSocket
WebSocket也是一個應用層通信,不同于可以實現倆類協議TCP/UDP的Socket,WebSocket是以HTTP/HTTPS連接、以TCP傳輸數據。
一旦握手成功,客戶端和服務器之間可以進行雙向數據傳輸,可以傳輸字節數據也可以傳輸文本內容。
持久連接:WebSocket 是持久化連接,除非主動關閉,否則在整個會話期間連接保持開放。
全雙工通信:客戶端和服務器可以隨時發送數據,通信不再是單向的。使用System.Net.WebSockets.ClientWebSocket類來實現WebSocket通信,通過減少 HTTP 請求/響應的開銷、延時較低。
而WebSocket與HttpClient呢,都用于應用層的網絡通信,但它們的用途和通信協議是不同的。
HttpClient使用 HTTP 協議,WebSocket使用WebSocket協議,該協議在初始連接時通過 HTTP/HTTPS握手,然后轉換為基于TCP通信的WebSocket協議。所以雖然都有使用HTTP協議,但WebSocket后續就切換至基于TCP的全雙工通信了
HttpClient基于請求/響應模式,每次通信由客戶端向服務器發起請求。WebSocket提供全雙工通信,客戶端和服務器都可以主動發送數據。
HttpClient主要用于訪問 RESTful API、下載文件或者發送HTTP請求。WebSocket主要用于實現低延遲的實時通信,如進程間通信、局域網通信等。
我團隊Windows應用所使用的進程間通信,就是基于WebSocketSharp封裝的。WebSocketSharp是一個功能全面、易于使用的第三方 WebSocket 庫 GitHub - sta/websocket-sharp
至于為啥不直接使用ClientWebSocket。。。是因為當時團隊還未切換.NET,使用的是.NETFramework。
后面團隊使用的局域網通信基礎組件就是用ClientWebSocket了。
下面是我封裝的部分WebSocket通信代碼,事件發送(廣播)、以及監聽其它客戶端發送過來的事件消息:
/// <summary>
/// 發送消息
/// </summary>
/// <typeparam name="TInput">發送參數類型</typeparam>
/// <param name="client">目標客戶端</param>
/// <param name="innerEvent">事件名</param>
/// <param name="data">發送參數</param>
/// <returns></returns>
public async Task<ClientResponse> SendAsync<TInput>(string client, InnerEventItem innerEvent, TInput data)
{
var message = new ChannelSendingMessage(client, new ClientEvent(innerEvent.EventName, innerEvent.EventId, true), _sourceClient);
message.SetData<TInput>(data);
return await SendMessageAsync(ChannelMessageType.ClientCommunication, message);
}
/// <summary>
/// 訂閱消息
/// </summary>
/// <param name="client">目標客戶端</param>
/// <param name="innerEvent">事件名稱</param>
/// <param name="func">委托</param>
public ClientSubscribedEvent SubscribeFunc(string client, InnerEventItem innerEvent, Func<ClientResponse, object> func)
{
var eventName = innerEvent?.EventName;
if (string.IsNullOrEmpty(eventName) || func == null)
{
throw new ArgumentNullException($"{nameof(eventName)}或{nameof(func)},參數不能為空!");
}
var subscribedEvent = new ClientSubscribedEvent(client, innerEvent, func);
SubscribeEvent(subscribedEvent);
return subscribedEvent;
}
/// <summary>
/// 訂閱消息
/// </summary>
/// <param name="client">目標客戶端</param>
/// <param name="innerEvent">事件名稱</param>
/// <param name="func">委托</param>
public ClientSubscribedEvent SubscribeFuncTask(string client, InnerEventItem innerEvent, Func<ClientResponse, Task<object>> func)
{
var eventName = innerEvent?.EventName;
if (string.IsNullOrEmpty(eventName) || func == null)
{
throw new ArgumentNullException($"{nameof(eventName)}或{nameof(func)},參數不能為空!");
}
var subscribedEvent = new ClientSubscribedEvent(client, innerEvent, func);
SubscribeEvent(subscribedEvent);
return subscribedEvent;
}
/// <summary>
/// 訂閱消息
/// </summary>
/// <param name="client">目標客戶端</param>
/// <param name="innerEvent">事件名稱</param>
/// <param name="action">委托</param>
public ClientSubscribedEvent Subscribe(string client, InnerEventItem innerEvent, Action<ClientResponse> action)
{
var eventName = innerEvent?.EventName;
if (string.IsNullOrEmpty(eventName) || action == null)
{
throw new ArgumentNullException($"{nameof(eventName)}或{nameof(action)},參數不能為空!");
}
var subscribedEvent = new ClientSubscribedEvent(client, innerEvent, action);
SubscribeEvent(subscribedEvent);
return subscribedEvent;
}
作者:唐宋元明清2188
出處:http://www.cnblogs.com/kybs0/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須在文章頁面給出原文連接,否則保留追究法律責任的權利。
該文章在 2024/9/5 11:46:49 編輯過