C # -PHP socket connection

I am writing a program on a PC that is controlled using a php script on a server. I am currently using php for an ftp file back and forth and using C # to read the file and execute commands based on the data in the file. However, this is not an ideal solution.

I would like to see a tutorial or example on how to use php to send data to pver C # program sockets.

Sample data that I would like to send

1:control1 1:control2 1:control3 0:control4 0:control5 

Can someone point me in the right direction?

+4
source share
2 answers

Instead of trying to get your server-side PHP script to send data to a C # program, which will give you a bunch of headaches, why not write something in a PHP script, which, given a specific request to the page, puts the current queues in the queue? Then the C # program can just do a WebRequest on the page and get its instructions.

For instance:

== php script ==

 <?php //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"; } ?> 

Now to actually retrieve data from the query:

== C # code code ==

 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; } 

This is a rough template with minimal error handling, I hope this is enough to get you started.

EDIT: Woops forgot to include a usage example:

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

you can use soap extensions for PHP to create a SOAP WebService that you can easily call from C #. It is as if you have gained access and you do not need to create your own protocol.

0
source

Source: https://habr.com/ru/post/1402467/


All Articles