简体   繁体   English

PHP - C# TCP 客户端/服务器如何发送字符串?

[英]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.嘿,我这里有一个 C# Tcp 服务器,这里有一个 PHP 客户端都在工作。

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 ?我的问题是现在如何调用我的 ping .. 然后发送 1 个或多个字符串并在我的服务器中捕获它们以控制它们或其他什么? ... ...

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 ?我之前已经在 VB 中做过这件事,所以我知道我可以用 Streamreader 和 Write 做到这一点,但我想这在这里不起作用? 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.这意味着命令 ping,带有参数 string1 和 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:和 PHP 代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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