通过套接字将数据从浏览器客户端发送到WPF应用程序服务器

时间:2019-07-04 02:42:32

标签: c# wpf sockets

我使用WPF MVVM创建了一个应用程序,该应用程序将侦听通过套接字发出的任何请求。现在说我想从浏览器PHP发送数据。我已经编写了所有代码,但似乎没有连接。没有错误,所以我无法弄清楚它出了什么问题。有人能帮我吗?我是WPF环境的新手。我非常确定我的WPF代码配置不正确。

phpcode

<?php
$host    = "127.0.0.1";
$port    = 3309;
$message = "Hello Server";
echo "Message To server :".$message."<EOF>";
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create    socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server  :".$result;
// close socket
socket_close($socket); ?>

wpfcode

public static void StartServer()
    {
        Console.WriteLine("start server");
        // Get Host IP Address that is used to establish a connection  
        // In this case, we get one IP address of localhost that is IP : 127.0.0.1  
        // If a host has multiple addresses, you will get a list of addresses  
        IPHostEntry host = Dns.GetHostEntry("localhost");
        IPAddress ipAddress = host.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 3309);


        try
        {

            // Create a Socket that will use Tcp protocol      
            Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            // A Socket must be associated with an endpoint using the Bind method  
            listener.Bind(localEndPoint);
            // Specify how many requests a Socket can listen before it gives Server busy response.  
            // We will listen 10 requests at a time  
            listener.Listen(10);

            Console.WriteLine("Waiting for a connection...");
            Socket handler = listener.Accept();

            // Incoming data from the client.    
            string data = null;
            byte[] bytes = null;

            while (true)
            {
                bytes = new byte[1024];
                int bytesRec = handler.Receive(bytes);
                data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                if (data.IndexOf("<EOF>") > -1)
                {
                    break;
                }
            }

            Console.WriteLine("Text received : {0}", data);

            byte[] msg = Encoding.ASCII.GetBytes(data);
            handler.Send(msg);
            handler.Shutdown(SocketShutdown.Both);
            handler.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\n Press any key to continue...");
        Console.ReadKey();
    }

0 个答案:

没有答案