简体   繁体   English

为什么在PHP和android中尝试使用套接字时连接被拒绝?

[英]why connection is refused while trying to use socket in PHP and android?

why i get java.net.ConnectException: /192.168.1.5:6789 - Connection refused? 为什么我得到java.net.ConnectException:/192.168.1.5:6789-连接被拒绝?

i am using php and android java code. 我正在使用php和android java代码。 before asking this question i checked questions like java.net.ConnectException: Connection refused . 在问这个问题之前,我检查了java.net.ConnectException之类的问题:Connection拒绝 while there were useful but they could not solve my problem. 虽然有用,但无法解决我的问题。

the scenario is 情况是

1- i am using XAMPP 1-我正在使用XAMPP

2- windows firewall is off 2- Windows防火墙关闭

3- when i run php script i can see port 6789 is set to listening by checking netstat -a 3-当我运行php脚本时,我可以通过检查netstat -a看到端口6789设置为侦听

4- java "android" code : 4- Java“ Android”代码:

    try
        {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);//"192.168.1.5" the PC which XAMPP is runing on
            socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);//6789
        }
        catch (UnknownHostException e1)
        {
            e1.printStackTrace();
        }
        catch (IOException e1)
        {
            e1.printStackTrace();
        }

5- php code 5- PHP代码

 <?php
set_time_limit( 0 );
$address = '127.0.0.1';
$port = 6789;
$sock = socket_create( AF_INET, SOCK_STREAM, 0 ); // 0 for  SQL_TCP
socket_bind( $sock, 0, $port ) or die( 'Could not bind to address' );  
socket_listen( $sock );
  while (true) {
    $client = socket_accept( $sock );
    $input = socket_read( $client, 1024000 );
    socket_write( $client, $response );
    socket_close( $client );
 }

socket_close( $sock );

6- i run php script and it keeps loading that mean it is listening and is in while block 6-我运行php脚本,并且不断加载,这意味着它正在监听并且处于while块中

7- i start the android app and i get this notification 7-我启动android应用程序,并收到此通知

java.net.ConnectException: /192.168.1.5:6789 - Connection refused java.net.ConnectException:/192.168.1.5:6789-连接被拒绝

and finally i am sure that PC(server) IP address is correct and in manifests internet permission is set 最后,我确定PC(服务器)的IP地址是正确的,并且在清单中明确设置了互联网许可

thank you in advance! 先感谢您!

I don't think that socket_create( AF_INET, SOCK_STREAM, 0 ); 我不认为socket_create( AF_INET, SOCK_STREAM, 0 ); is correct. 是正确的。 The third number is the protocol number, and the documentation says that you should be using the SOL_TCP constant for that. 第三个数字是协议编号,并且文档说您应该SOL_TCP使用SOL_TCP常量。

The value 0 is the protocol number for IP. 值0是IP的协议号。 The protocol number for TCP is 6. Both of these are according to "/etc/protocols" on my Linux machine ... which is the definitive source according to the documentation / comments for socket_create and getprotobynumber . TCP的协议号为6。这两个都是根据我的Linux机器上的“ / etc / protocols” ...,根据socket_create / socket_creategetprotobynumber的文档/注释,这是确定的来源。

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

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