简体   繁体   English

PHP套接字被客户端强制关闭

[英]PHP socket closing forcibly by client

I created a PHP's socket server. 我创建了一个PHP的套接字服务器。 I connected to it using telnet or putty and everything works just well, until I tried to connect to in a .Net application, each time I execute the app it closes the server, here's my C# code, just the two lines: 我使用telnet或腻子连接到它,并且一切正常,直到尝试连接到.Net应用程序为止,每次我执行该应用程序时,它都会关闭服务器,这是我的C#代码,只有两行:

System.Net.Sockets.TcpClient cli = new System.Net.Sockets.TcpClient("192.168.0.200", 10000);
cli.Close();

When I run the app the PHP socket server is closed with this error: 当我运行应用程序时,PHP套接字服务器因以下错误而关闭:

Warning: socket_read(): unable to read from socket [0]: An existing connection was forcibly closed by the remote host

I tried commenting out the Cli.close() line, and sure enough the socket stayed open until the C# app is closed, then it will close with the same error message above. 我尝试注释掉Cli.close()行,并确保套接字一直保持打开状态,直到关闭C#应用程序为止,然后它将关闭,并显示与上面相同的错误消息。

So what is causing the problem?, client should not be able to close the socket this way. 那么是什么原因引起的呢?客户端应该不能以这种方式关闭套接字。

Thank you 谢谢

Looking at the code at http://php.net/manual/en/sockets.examples.php I do not see any problems with it. 查看http://php.net/manual/en/sockets.examples.php上的代码,我看不到任何问题。 This code exists the script when socket is closed: 套接字关闭时,此代码存在脚本:

if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
        echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
        break 2;
    }

What I can suggest is to modify the code as follow: 我可以建议修改代码如下:

if (false === ($buf = @socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
        echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
        break;
    }

Adding '@' will prevent warning to appear. 添加“ @”将防止出现警告。 Changing break 2; 更改break 2; to break; break; will make server not to exit but to keep waiting for a next connection. 将使服务器不会退出,而是继续等待下一个连接。

If this doesn't work than you can wrap the whole script to another do { } while() loop so that every time the socket read fails php do socket_create() again. 如果这不起作用,那么您可以将整个脚本包装到另一个do { } while()循环中,以便每次套接字读取php失败时都再次执行socket_create()

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

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