qreader php,C#-PHP套接字连接

我正在通过服务器上的php脚本控制的PC上编写程序.我目前正在使用php来来回ftp文件并使用c#读取文件并根据文件中的数据执行命令.然而,这不是一个理想的解决方案.

我想看一个关于如何使用php将数据发送到c#程序pver套接字的教程或示例.

我想发送的数据示例

1:control1

1:control2

1:control3

0:control4

0:control5

谁能指出我正确的方向?

解决方法:

而不是尝试让你的服务器端PHP脚本将数据发送到C#程序,这将给你带来一堆令人头疼的问题,为什么不在PHP脚本上写一些东西,给定页面的特定请求,输出当前排队的说明?然后,C#程序可以只对页面进行WebRequest并接收其指令.

例如:

== PHP SCRIPT ==

//main execution.

process_request();

function process_request()

{

$header = "200 OK";

if (!empty($_GET['q']) && validate_request())

{

switch ($_GET['q'])

{

case "get_instructions":

echo get_instructions();

break;

case "something_else":

//do something else depending on what data the C# program requested.

break;

default:

$header = "403 Forbidden"; //not a valid query.

break;

}

}

else { $header = "403 Forbidden"; } //invalid request.

header("HTTP/1.1 $header");

}

function validate_request()

{

//this is just a basic validation, open to you for how you want to validate the request, if at all.

return $_SERVER["HTTP_USER_AGENT"] == "MyAppName/1.1 (Instruction Request)";

}

function get_instructions()

{

//pseudo function, for example purposes only.

return "1:control1\n1:control2\n1:control3\n0:control4\n0:control5";

}

?>

现在实际从请求中检索数据:

== C#客户代码==

private string QueryServer(string command, Uri serverpage)

{

string qString = string.Empty;

HttpWebRequest qRequest = (HttpWebRequest)HttpWebRequest.Create(serverpage.AbsoluteUri + "?q=" + command);

qRequest.Method = "GET";

qRequest.UserAgent = "MyAppName/1.1 (Instruction Request)";

using (HttpWebResponse qResponse = (HttpWebResponse)qRequest.GetResponse())

if (qResponse.StatusCode == HttpStatusCode.OK)

using (System.IO.StreamReader qReader = new System.IO.StreamReader(qResponse.GetResponseStream()))

qString = qReader.ReadToEnd().Trim(); ;

return qString;

}

这是一个粗略的模板,具有最小的错误处理,希望它足以让您入门.

编辑:Woops,忘了包含一个示例用法:

MessageBox.Show(QueryServer("get_instructions", new Uri("http://localhost/interop.php")));

标签:php,c,sockets

来源: https://codeday.me/bug/20190704/1376844.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值