我最终选择了一个 Web API,它让我通过 HTTP 协议从服务器“调用”函数。URL 是函数的“名称”,数据要么在正文中序列化,要么在 URL 中序列化。非常简单和灵活,它应该在任何可以使用 HTTP 的框架上开箱即用,或者我可能能够找到一个让我这样做的库。
我的测试代码如下所示:
客户:
private async Task SubmitJob()
{
JobModel job = new JobModel { ID = 42, name = "HelloJob", completion = 100.0f };
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsJsonAsync<JobModel>("http://localhost:53122/Jobs/Submit", job);
if (response.IsSuccessStatusCode)
lblSuccess.Text = "Success!";
else
lblSuccess.Text = "Failure!";
}
catch (Exception ex)
{
string s = ex.ToString();
}
}
private async Task GetJobs()
{
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost:53122/Jobs/Info");
if (response.IsSuccessStatusCode)
{
List<JobModel> jobList = await response.Content.ReadAsAsync<List<JobModel>>();
txtConsole.Text = "";
foreach(var job in jobList)
{
string line = "ID: " + job.ID + " Name: " + job.name + " completion: " + job.completion + "\r\n";
txtConsole.Text += line;
}
}
else
{
txtConsole.Text = "Failure!";
}
}
catch (Exception ex)
{
string s = ex.ToString();
}
}
服务器:
public async Task<IHttpActionResult> GetJobInfo(int jobId)
{
try
{
JobModel a = new JobModel { name = "jobA", ID = 102, completion = 100.0f };
JobModel b = new JobModel { name = "jobB", ID = 104, completion = 42.0f };
JobModel c = new JobModel { name = "jobC", ID = 106, completion = 0.0f };
List<JobModel> result = new List<JobModel> { a, b, c };
return Ok(result);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[HttpPost]
public async Task<IHttpActionResult> SubmitJob([FromBody] JobModel submitedJob)
{
return Ok();
}