-1

这是 android 应用程序中的一个方法,在 web 服务器中收听 php 文件发送的消息

public void run() {

try {
    Log.i("------Connect--------", "------------1-------------");
    //System.out.println("S: Connecting...");
    ServerSocket serverSocket = new ServerSocket(SERVERPORT);
    Log.i("------xxxxxxxxx--------", "------------2-------------");

    while (true) {
        x++;
        Log.i("------xxxxxxxxxx--------","-----------"+x+"-----------");
        Log.i("------xxxxxxxxxx--------", "-----------pret de listener------------");
        Socket client = serverSocket.accept();
        Log.i("------xxxxxxxxxx--------", "-----------en cours de listening-------------");

        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            String str = in.readLine();
            Log.i("------xxxxxxxxxx--------", str + "-------------");
            //System.out.println("S: Received: '" +);

        } catch(Exception e) {
            Log.i("------xxxxxxxxxx--------", "S: Error");

        } finally {
            client.close();
            Log.i("------xxxxxxxxxx--------","S: Done.");
        }

    }

} catch (Exception e) {
    Log.i("------xxxxxxxxxx--------","S: Error");
}

下一个 php 代码将字符串从模拟器 android 发送到 ip

<?php

error_reporting(E_ALL);

/* define socket server ip and port here.. */
$socket_ip = "10.0.0.2";

$socket_port = 6060;

set_time_limit(0);
/* create a tcp/ip socket.. */
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === false) {
    $error = socket_strerror(socket_last_error());
    echo "socket_create() failed: [$result] $error\n";
} else {
    echo "socket_create() ok.\n";
}

/* connect to socket server ip and port */
$result = socket_connect($socket, $socket_ip, $socket_port);
if ($result === false) {
    $error = socket_strerror(socket_last_error($socket));
    echo "socket_connect() failed: [$result] $error\n";
} else {
    echo "socket_connect() ok.\n";
}

$in = "\r\n\r\n";
$len = strlen($in);

echo "sending input data request.\n";
socket_write($socket, $in, $len);
echo "socket_write() ok.\n";

echo "reading return data.\n";
while ($out = socket_read($socket, 6060)) {
    echo "socket_read() : $out";
}

echo "closing the socket.";
socket_close($socket);
echo "socket_close() ok.\n\n";
?>

问题是当执行命令'$ result = socket_connect($ socket, $ socket_ip, $ socket_port);'找不到答案

4

1 回答 1

0

如果要从服务器中提取数据,请使用 Josephs 教程。如果您想将数据从服务器推送到手机,请使用Google Cloud Messaging。这样,服务器可以让电话知道有新数据可用。你仍然需要拉它。您不应该通过套接字将数据推送到手机。

于 2013-04-15T23:09:24.117 回答