废话不说,直接上代码
我是在控制台里面测试的服务器功能,下面是功能类
public class TestHttpServer
{
HttpServer server;
public TestHttpServer()
{
server = new HttpServer();
server.RegisterHttpRpcApi(this.GetType()); // 注册一个POST请求的API
server.Start(5000);
}
public void Close()
{
server?.Close();
}
[HslMqttApi(HttpMethod = "GET")]
public static int Calculate(int a, int b)
{
int x = a * 10 + b * 2;
return x; // 假设这个就是我们的核心的算法
//return 6666;
}
[HslMqttApi(HttpMethod = "POST")]
public static int Add(int a, int b)
{
return a + b;
}
/// <summary>
/// 打标机做HTTP服务器接口
/// </summary>
/// <param name="INV_ORG_ID"></param>
/// <param name="line_code"></param>
/// <param name="Upload_mode"></param>
/// <param name="create_time"></param>
/// <param name="barcode"></param>
/// <returns></returns>
[HslMqttApi(HttpMethod = "POST")]
public static ResultInfo accessElecBill(string INV_ORG_ID, string line_code, string Upload_mode, DateTime create_time, List<string> barcode)
{
/* 接受到的数据 存入表格显示,委托出去
string all = INV_ORG_ID + line_code + Upload_mode + create_time;
for (int i = 0; i < barcode.Count; i++)
{
all += barcode[i];
}
*/
ResultInfo resultInfo = new ResultInfo();
if (barcode == null)
{
resultInfo.code = "1";
resultInfo.msg = "条码barcode==null";
resultInfo.errMsg = null;
resultInfo.timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
resultInfo.data = null;
}
else
{
resultInfo.code = "0";
resultInfo.msg = "发送成功";
resultInfo.errMsg = null;
resultInfo.timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
resultInfo.data = barcode.Count.ToString();
}
return resultInfo;
}
}
public class ResultInfo
{
/// <summary>
/// 默认0 成功,1 失败
/// </summary>
public string code { get; set; }
/// <summary>
/// 调用成功信息或者错误信息
/// </summary>
public string msg { get; set; }
public string errMsg { get; set; }
/// <summary>
/// 返回时间
/// </summary>
public string timestamp { get; set; }
public string data { get; set; }
}
我看手册里面都是在Program里面测试的,我怕不能在其他类里测试,所以就单独写了一个类调用,测试结果是正常,可以在其他类里面。
main函数里面代码
internal class Program
{
static void Main(string[] args)
{
TestHttpServer testHttpServer = new TestHttpServer();
Console.WriteLine( "nihao");
Console.ReadLine();
}
}
业务接口
函数设计
使用POST 直接设计函数入参就行,hsl的http会自动把body的json 转为对象类型。