简体   繁体   中英

PHP - C# TCP Client / Server How to send Strings ?

Hey i have here aa 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 :)

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>";
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM