简体   繁体   English

PHP客户端套接字与C#套接字服务器的连接

[英]PHP client socket connection with C# Socket Server

I am trying to connect to my C# server from my website using PHP. 我正在尝试使用PHP从我的网站连接到C#服务器。

I would like to keep the connection alive through all pages. 我想在所有页面上保持活动连接。

C# Server: Port 100 C#服务器:端口100

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

namespace Multi_Server
{
    class Program
    {
        private static Socket _serverSocket;
        private static readonly List<Socket> _clientSockets = new List<Socket>();
        private const int _BUFFER_SIZE = 2048;
        private const int _PORT = 100;
        private static readonly byte[] _buffer = new byte[_BUFFER_SIZE];

        static void Main()
        {
            Console.Title = "Server";
            SetupServer();
            Console.ReadLine(); // When we press enter close everything
            CloseAllSockets();
        }

        private static void SetupServer()
        {
            Console.WriteLine("Setting up server...");
            _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, _PORT));
            _serverSocket.Listen(5);
            _serverSocket.BeginAccept(AcceptCallback, null);
            Console.WriteLine("Server setup complete");
        }

        /// <summary>
        /// Close all connected client (we do not need to shutdown the server socket as its connections
        /// are already closed with the clients)
        /// </summary>
        private static void CloseAllSockets()
        {
            foreach (Socket socket in _clientSockets)
            {
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }

            _serverSocket.Close();
        }

        private static void AcceptCallback(IAsyncResult AR)
        {
            Socket socket;

            try
            {
                socket = _serverSocket.EndAccept(AR);
            }
            catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets)
            {
                return;
            }

           _clientSockets.Add(socket);
           socket.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
           Console.WriteLine("Client connected, waiting for request...");
           _serverSocket.BeginAccept(AcceptCallback, null);
        }

        private static void ReceiveCallback(IAsyncResult AR)
        {
            Socket current = (Socket)AR.AsyncState;
            int received;

            try
            {
                received = current.EndReceive(AR);
            }
            catch (SocketException)
            {
                Console.WriteLine("Client forcefully disconnected");
                current.Close(); // Dont shutdown because the socket may be disposed and its disconnected anyway
                _clientSockets.Remove(current);
                return;
            }

            byte[] recBuf = new byte[received];
            Array.Copy(_buffer, recBuf, received);
            string text = Encoding.ASCII.GetString(recBuf);
            Console.WriteLine("Received Text: " + text);

            if (text.ToLower() == "get time") // Client requested time
            {
                Console.WriteLine("Text is a get time request");
                byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString());
                current.Send(data);
                Console.WriteLine("Time sent to client");
            }
            else if (text.ToLower() == "exit") // Client wants to exit gracefully
            {
                // Always Shutdown before closing
                current.Shutdown(SocketShutdown.Both);
                current.Close();
                _clientSockets.Remove(current);
                Console.WriteLine("Client disconnected");
                return;
            }
            else
            {
                Console.WriteLine("Text is an invalid request");
                byte[] data = Encoding.ASCII.GetBytes("Invalid request");
                current.Send(data);
                Console.WriteLine("Warning Sent");
            }

            current.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
        }
    }
}

I am using http://php.net/manual/en/book.sockets.php 我正在使用http://php.net/manual/en/book.sockets.php

Please do not suggest alternatives (this is a fallback option for non compatible HTML5 browsers) 请不要提出其他建议(对于不兼容的HTML5浏览器,这是一个后备选项)

PHP: PHP:

<?PHP
 $service_port = 100;
  $address = '10.10.10.12';

  $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  socket_set_nonblock($socket);

socket_connect($socket, $address, $service_port);

?>

My php code is causing an error on my server when connected. 连接时,我的PHP代码导致服务器上的错误。 https://www.anony.ws/i/2015/06/02/Capture1aa49.png https://www.anony.ws/i/2015/06/02/Capture1aa49.png

I am having the same issue when trying to connect via python.. 尝试通过python连接时出现相同的问题。

#!/Python34/python
import socket
HOST = '10.10.10.12'    # The remote host
PORT = 100             # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))

I was able to track down the error... Still not to sure what is causing it.. Message : A TCPIP socket error has occurred (10053): An established connection was aborted by the software in your host machine. 我能够跟踪该错误...仍然不确定是什么原因引起的。.消息:发生TCPIP套接字错误(10053):建立的连接被主机中的软件中止了。 Reason : The server closed the client connection. 原因:服务器关闭了客户端连接。 Action : Contact the network administrator or server administrator. 行动:与网络管理员或服务器管理员联系。

The error is happening won the Begin Receive for the server, which is causing the server to close the connection. 在服务器的“开始接收”中发生了错误,这导致服务器关闭连接。 I believe i am sending information to the server incorrectly, if i take out the receive for the server the connection is not terminated. 我相信我将信息错误地发送到服务器,如果我取出服务器的接收,连接不会终止。

keeping a connection open with PHP is not good practice and will cause the page to not finish loading. 保持与PHP的连接打开不是一种好习惯,并且会导致页面无法完成加载。 PHP should be closed by the time the web browser receives its output. Web浏览器收到输出时,应关闭PHP。 consider using Javascript not PHP. 考虑使用Javascript而不是PHP。 The reason you connection closes is the handshake. 连接关闭的原因是握手。

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

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