You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.7 KiB
C#

using Sln.Iot.Serilog;
using System.Text;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Sockets;
using HttpClient = TouchSocket.Http.HttpClient;
namespace Sln.Iot.Socket
{
public class DeltaHttpClient
{
private static readonly Lazy<DeltaHttpClient> lazy = new Lazy<DeltaHttpClient>(() => new DeltaHttpClient());
public static DeltaHttpClient Instance
{
get
{
return lazy.Value;
}
}
HttpClient DeltaClent = new HttpClient();
SerilogHelper _log = SerilogHelper.Instance;
/// <summary>
/// 连接台达MES服务器
/// </summary>
public async void Init()
{
try
{
var config = new TouchSocketConfig();
#region Http设置远程服务器地址
config.SetRemoteIPHost("http://10.148.192.32:8090");
#endregion
#region Http客户端获取断线通知
config.ConfigurePlugins(a =>
{
a.AddTcpClosedPlugin(async (c, e) =>
{
Console.WriteLine("客户端断开连接");
await e.InvokeNext();
});
});
#endregion
//配置config
await DeltaClent.SetupAsync(config);
await DeltaClent.ConnectAsync();//先做连接
}
catch (Exception ex)
{
_log.Error("MES连接失败请检查网线连接", ex);
}
}
/// <summary>
/// post请求发送数据到台达MES
/// </summary>
/// <param name="jsonData"></param>
public async void PostRequestSend(string jsonData)
{
var request = new HttpRequest();
request.SetContent(new StringHttpContent(jsonData, Encoding.UTF8, "application/json"))
.InitHeaders()
.SetUrl("/sensordata?sensorId=UploadMachineData")
.SetHost(DeltaClent.RemoteIPHost.Host)
.AsPost();
try
{
//创建一个超时操作10秒后取消。
using var cts = new CancellationTokenSource(1000 * 10);
using (var responseResult = await DeltaClent.RequestAsync(request, cts.Token))
{
var response = responseResult.Response;
var result = await response.GetBodyAsync();
_log.Info($"响应结果:{result}");
}
}
catch (Exception ex)
{
_log.Error("请求发送失败", ex);
}
}
}
}