3

Hey i have here a a C# Tcp Server and here a PHP Client both are working.

SERVER

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace ConsoleApplication2
{
    class Program
    {


        public static void Main()
        {
            try
            {
                IPAddress ipAd = IPAddress.Parse("127.0.0.1");
                TcpListener myList = new TcpListener(ipAd, 8001);

                myList.Start();

                Console.WriteLine("The server is running at port 8001...");
                Console.WriteLine("The local End point is  :" +
                                  myList.LocalEndpoint);
                Console.WriteLine("Waiting for a connection.....");


                while (true)
                {

                Socket s = myList.AcceptSocket();
                Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

                byte[] b = new byte[100];
                int k = s.Receive(b);
                string szReceived = Encoding.ASCII.GetString(b.Take(k).ToArray());
                Console.WriteLine(szReceived);
                Console.WriteLine("Recieved..." + szReceived + "---");

                switch (szReceived)
                {
                    case "ping":
                        Console.WriteLine("Ping wird ausgeführt!");
                        ASCIIEncoding asen = new ASCIIEncoding();
                s.Send(asen.GetBytes("PONG !"));
                        s.Close();

                        break;

                    case "logout":

                        break;
                }


                }




                /* clean up */

                    myList.Stop();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }



        }



    }
}

CLIENT

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<?PHP

error_reporting(E_ALL);
ini_set("display_errors", 1);

$address="127.0.0.1";
$service_port = "8001";

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: <br>" . 
         socket_strerror(socket_last_error()) . "\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...<br>";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) <br>" . 
          socket_strerror(socket_last_error($socket)) . "\n";
}else {

 echo "connected<br>";


}

$in = "ping";
$out = '';

echo "Client Sended: PING !<br>";

socket_write($socket, $in, strlen($in));
echo "SENDED!.\n<br>";

echo "Reading response:\n\n<br>";

while ($out = socket_read($socket, 2048)) {
echo $out;
}

socket_close($socket);

?>

My Question is now how can i call now my ping .. and then sending 1 or more Strings behind and catch them in my Server to Console them or whateve ? ...

I already did this in VB earlier so i know it is possible i did it with Streamreader and Write but i guess this isnt working here ? Code examples would be very helpfull

Thanks for every Answer :)

Hanselman
  • 171
  • 1
  • 2
  • 8

1 Answers1

1

You must define a protocol for yourself and use it to send anything. For example send something like this:

ping|string1,string2

Which means command ping, with parameters string1 and string2. You can define anything that covers your needs. And then just send them in this format, and parse it other side.

This is an example based on your code. Take a look at this (some parts of unchanged code is omitted for readability):

....

Console.WriteLine(szReceived);
Console.WriteLine("Recieved..." + szReceived + "---");

var split = szReceived.Split('|');
if(split.Length==0)return;

var command = split[0];
var parameters = new string[0];

if (split.Length > 0)
    parameters = split[1].Split(',');

switch (command)
{
    case "ping":
        Console.WriteLine("Ping wird ausgeführt!");
        ASCIIEncoding asen = new ASCIIEncoding();

        foreach (var p in parameters)
            Console.WriteLine(p);

        s.Send(asen.GetBytes("PONG !"));
        s.Close();

        break;

    case "logout":

        break;
}
....

And the PHP code:

...
$stringsToSend = array("Hello", "World!", "Sth");

$in = "ping|" . implode(",", $stringsToSend);
$out = '';

echo "Client Sended: PING !<br>";

socket_write($socket, $in, strlen($in));
echo "SENDED!.\n<br>";
...
Ahmad
  • 5,551
  • 8
  • 41
  • 57
  • you should actually use Tag Length Value format of messing, it will make ur life simple. https://en.wikipedia.org/wiki/Type-length-value – Parimal Raj Sep 05 '15 at 18:26
  • Maybe. Depends on the usage. He just wants strings to be sent and this way is more simple, I think. Specially as I know, .NET does not have a built in parser for that. – Ahmad Sep 05 '15 at 18:34
  • @Ahmad Thanks for this detailed Answer! :) but how can i get now like when i send now $String1 and i need at other site this as string String1 ? So how can i get it back into a variable? – Hanselman Sep 05 '15 at 19:31
  • @Ahmad How can i get the parameter into a Variable in the Server ? like i send $email... to Server and on Server i want then too the Email in the $email variable ? – Hanselman Sep 05 '15 at 20:33
  • 1
    @Hanselman the `parameters` is an array of parameters sent from the client. For example if you have sent the array `$stringsToSend = array($email, $sth);` then you will have this array on the server in `parameters` and you can use its values, like `string Email = parameters[0], Sth = parameters[1]` – Ahmad Sep 05 '15 at 20:51
  • @Ahmad is there a way to make a listener in the php File ? – Hanselman Sep 05 '15 at 22:26
  • 1
    @Hanselman PHP runs on a web server, and the duty of web server is listening! PHP is always listening. You only have to request it in HTTP. .NET has some classes for that. Take a look at this http://stackoverflow.com/questions/4015324/http-request-with-post – Ahmad Sep 06 '15 at 11:14
  • @Ahmad Okey yeah i mean like looped so that the Server sends ping (like in this question as Example) and Client react to this ... – Hanselman Sep 06 '15 at 13:53
  • @Ahmad like that the Client is everytime reacting when Server sends sometthing ? – Hanselman Sep 06 '15 at 14:06
  • @Hanselman Sorry, but I could not understand your question. Please describe it as an example (and a little more clear) – Ahmad Sep 06 '15 at 18:04