这是 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);'找不到答案