PLC总控改造(2)

WebAPI:用于从站向主站推送相关内容

从站编写:

using Newtonsoft.Json;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Text;

public static class WebAPIClientHelper

{

// 主站的IP地址

private static string url = "http://XXXXX:2002/api/push/";

/// <summary>

/// 外部调用:发送 string + 指定类型

/// </summary>

public static bool Send(string message, 指定类型 参数名)

{

try

{

// 组装要发送的数据

var sendObj = new

{

Message = message,

Parameter = parameter

};

// 转JSON

string json = JsonConvert.SerializeObject(sendObj);

byte\[\] data = Encoding.UTF8.GetBytes(json);

// 使用 .NET4.0 自带的 WebClient(不报错!)

using (WebClient client = new WebClient())

{

client.HeadersHttpRequestHeader.ContentType = "application/json";
byte\[\] result = client.UploadData(url, "POST", data);

string resp = Encoding.UTF8.GetString(result);

}

return true;

}

catch

{

return false;

}

}

}

主站编写:

using Newtonsoft.Json;

using System;

using System.Collections.Generic;

using System.IO;

using System.Net;

using System.Text;

using System.Threading;

public class WebAPIServer

{

private HttpListener _listener;

private bool _isRunning;

private Plugin plugin;

public void Start()

{

_listener = new HttpListener();

_listener.Prefixes.Add("http://*:2002/api/push/");//监听

_listener.Start();

_isRunning = true;

System.Threading.ThreadPool.QueueUserWorkItem(o =>

{

while (_isRunning)

{

try

{

var context = _listener.GetContext();

ProcessRequest(context);

}

catch { }

}

});

}

public WebAPIServer(Plugin pluginInstance)

{

plugin = pluginInstance ?? throw new ArgumentNullException(nameof(pluginInstance), "插件实例不能为null");

}

private void ProcessRequest(HttpListenerContext context)

{

try

{

using (var reader = new StreamReader(context.Request.InputStream, Encoding.UTF8))

{

string json = reader.ReadToEnd();

var data = JsonConvert.DeserializeObject<ReceiveData>(json);

string msg = data.Message;

MethodRuningParameter param = data.Parameter;

if (msg == "start")

{

RunStartTask(param);

}

else

{

RunDefault(msg, param);

}

var resp = new { code = 200, msg = "接收成功" };

string respJson = JsonConvert.SerializeObject(resp);

byte\[\] respBytes = Encoding.UTF8.GetBytes(respJson);

context.Response.ContentType = "application/json";

context.Response.OutputStream.Write(respBytes, 0, respBytes.Length);

}

}

catch

{

context.Response.StatusCode = 500;

}

finally

{

context.Response.Close();

}

}

private void RunStartTask(MethodRuningParameter p)

{

//业务逻辑

}

========================================================================

private void RunDefault(string msg, MethodRuningParameter p)

{

Console.WriteLine($"【默认处理】消息={msg}");

}

public void Stop()

{

_isRunning = false;

_listener?.Stop();

_listener?.Close();

}

}

//==================================================

// 定义接收实体

//==================================================

public class ReceiveData

{

public string Message { get; set; }

public MethodRuningParameter Parameter { get; set; }

}

}

相关推荐
csdn_aspnet4 天前
.NetCore Webapi 接口验证请求来源
.netcore·ip·token·签名·webapi·cors·sign
DreamLife☼12 天前
西门子 S7 系列协议深度科普
webapi·profinet·profibus·工业知识点·iso-on-tcp·串口时代·工业以太网时代
桔子雨17 天前
轻量,再轻量:当 PicoServer 遇上 SimdPaddleOCR
webapi·picoserver·轻量web框架
厦门德仔24 天前
【YiFeiWebApi】易飞ERP接口开发踩坑实录(避坑指南)
webapi·易飞·开放指南
桔子雨2 个月前
PicoServer的哲学:不是框架,是胶水
webapi·picoserver
桔子雨4 个月前
C# ESP32/STM32 轻量 Web 能力库:PicoServer.Nano
esp32·webapi·picoserver·picoserver.nano
.NET修仙日记5 个月前
2026 .NET 面试八股文:高频题 + 答案 + 原理(进阶核心篇)
面试·职场和发展·c#·.net·.net core·微软技术·webapi
csdn_aspnet5 个月前
.Net 解决 Web API 中的“服务器响应状态码为 405(方法不允许)”错误
服务器·.net·webapi
Murphy20236 个月前
.net8 Swashbuckle.AspNetCore WEBAPI 配置要点记录
.net·swagger·webapi·swashbuckle