【问题标题】:connect multiple device android to the same php socket将多个设备android连接到同一个php套接字
【发布时间】:2021-05-15 01:14:30
【问题描述】:

我的问题是,当我尝试将 Android 应用程序与由 IP 标识的 Java 套接字和端口 4444 与由同一端口标识的 PHP 服务连接时,并保持此连接打开以通过 Android 应用程序接受多个连接。

因此,如果我们连接到 PHP,则使用第二台 Android 设备,我们将拥有与一台设备相同的通信通道,并且我们无法识别通过 PHP 连接的设备。

是否有可能通过 PHP 文件区分这两个连接或为两个设备实例化两个不同的 PHP 服务。

Android 代码:

 public String connect() {

        Socket socket = null;

        try {
             socket = new Socket();
                // This limits the time allowed to establish a connection in the case
                // that the connection is refused or server doesn't exist.
                 socket.connect(new InetSocketAddress(dstAddress, dstPort), context.getResources().getInteger(R.integer.time_out));
                // This stops the request from dragging on after connection succeeds.
            socket.setSoTimeout(context.getResources().getInteger(R.integer.time_out));


           //  socket = new Socket();
          //  socket.connect(new InetSocketAddress(dstAddress, dstPort), 2000);

            if (!socket.isConnected())
                throw new SocketException("Could not connect to Socket");


            DataInputStream DIStream = new DataInputStream(socket.getInputStream());
            DataOutputStream DOStream = new DataOutputStream(socket.getOutputStream());


            DOStream.write(numCmd.getBytes(), 0, numCmd.getBytes().length);
            DOStream.flush();

            response = DIStream.readLine();

            DOStream.close();
            DIStream.close();

            socket.close();


        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "{\"Error_no\":5000}";


        }  catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "{\"Error_no\":5000}";

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

            response = "{\"Error_no\":5000}";


        }  finally {
            if (socket != null) {
                try {
                    socket.close();
                    if(response == null){

                        response = "{\"Error_no\":5000}";
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();

                    response = "{\"Error_no\":5000}";
                }
            }
        }

       // Log.i("resp",response);


        return response;
    }

PHP 代码:

<?php

echo "service php started \n";
$version = '2.2.0';
$address = '10.164.2.1';
$port = 4444;
$timeout= 2;

$cmd = explode("*", str_replace(array("/"), "*",
    str_replace(" ","",shell_exec("netstat -tulpn | grep :".$port))));

    echo "pid ".$cmd[1];

$cmd[1] = substr_replace($cmd[1], '', 0, 6);

echo "pid ".$cmd[1];

exec("kill -9 $cmd[1]"); 

sleep(1);


$socketPath = 'unix:///home/root/sockets/local_iapp_socket';

// Create WebSocket.
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);

if(socket_bind($server, $address, $port)){
    
    echo "Connected with tcp socket \n";

}else{
    
    echo "connection with tc socket error \n";
}

socket_listen($server);

echo "server is listning  \n";

$socket_fd = connect_socket_local();

echo "connected to unix socket  \n";

while ($client = socket_accept($server)) {
    
    $num_cmd = socket_read($client, 5000);

    echo "Client Message : ".$num_cmd ."\n";
 
    if($socket_fd != false){
        
        $id=24;
        
        $len= strlen($num_cmd);
        
        $fwrite1 = fwrite($socket_fd, pack("L", $len),4);
        
        if($fwrite1  === false){
            
            $content = '{"Error_no":5000}';
            echo "fwrite1   a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
            exit;

        }
        
        $fwrite2 = fwrite($socket_fd,pack("L", $id),4);
        
        if($fwrite2  === false){
            
            $content = '{"Error_no":5000}';
            echo "fwrite2   a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
            exit;

        }
        
        $fwrite3 = fwrite($socket_fd,$num_cmd,strlen($num_cmd));
        
        
        if($fwrite3  === false){
            
            $content = '{"Error_no":5000}';
            echo "fwrite3   a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
            exit;

        }
    

        $content = fread($socket_fd, 5000) ;
        
        if( $content == null){
            
            echo "impossible d'atteindre la socket locale" . socket_strerror(socket_last_error()) . "\n";
            $content = '{"Error_no":5000}';
                
        }
        
    }else{
        
        $content = '{"Error_no":5000}';
        echo "problème de connexion" . socket_strerror(socket_last_error()) . "\n";
    }
    
    $json_resp = $content;
    
    echo "json_resp" . $json_resp."\n\r";

    socket_write($client, $json_resp,strlen($json_resp));
    
    socket_close($client);
    
}

socket_close($server);

function connect_socket_local()
{
    global $socketPath , $timeout;

    
        if (($socket_fd= stream_socket_client($socketPath , $errorno, $errorstr, $timeout)) === false) {
            echo "stream_socket_client a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
        }

    return $socket_fd;
}

?>

【问题讨论】:

  • 看来您的 shift 键出现故障,导致帖子无法阅读。
  • 我不明白你看不懂什么,因为我可以很好地阅读帖子
  • 为什么服务器需要知道连接的是哪个设备?
  • 管理机器的处理并知道连接了哪个设备以及移交哪个设备是一种功能需求

标签: php android sockets


【解决方案1】:

您可以为每个客户端运行单独的服务器进程。每个服务器进程都需要有一个唯一的 IP 地址或 TCP 端口。每个客户端都需要配置为连接到正确的服务器地址和端口。这很难管理且无法扩展。

在服务器端,可以得到对等地址,即客户端的IP地址和端口。在 PHP 中,您可以为此使用socket_getpeername()。但是,根据网络设置,这可能不是客户端本身的 IP 地址。它可以是中间网关或其他网络设备的 IP 地址。此外,客户端 IP 地址可能是动态的。

最好的解决方案是当客户端连接到服务器时,从客户端向服务器发送一些标识。这可以是名称或其他一些唯一标识。您必须更改客户端和服务器之间的协议才能支持这一点。客户需要知道何时以及如何发送标识。服务器需要知道何时以及如何接收标识。

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多