【发布时间】:2012-06-27 04:17:33
【问题描述】:
我在我的 android 设备上创建了一个简单的 ServerSocket 应用程序,我使用 telnet 进行连接,它工作正常(发送的消息显示在我的 logcat 窗口中)。问题;当我尝试从 php 页面建立连接时(我也在使用 PHP 套接字)。 Android socket 接受第一个连接,然后有点奇怪 - 有时他会读取从 PHP 发送的消息并将它们显示在 logcat 中,但通常它只接受第一个请求,然后......什么都没有
安卓端代码:
public class TestSocketActivity extends Activity {
private ServerSocket ss;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setSocket();
}
public void setSocket() {
try {
ss = new ServerSocket(7000);
System.out.println("Started");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Accept failed: 4444");
e.printStackTrace();
}
Socket clientSocket = null;
try {
clientSocket = ss.accept();
String s = clientSocket.getRemoteSocketAddress().toString();
System.out.println(s);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("SS error");
e.printStackTrace();
}
try {
BufferedReader in =
new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
while ((inputLine = in.readLine()) != null) {
Toast.makeText(getApplicationContext(),"test",1).show();
System.out.println("in: "+inputLine);
}
ss.close();
setSocket();
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("error");
e.printStackTrace();
}
}
}
这是一个简单的 PHP 请求:
<?php
error_reporting(E_ALL);
$address = '192.168.0.180';
$port = 7000;
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
$result = socket_connect($socket, $address, $port);
$in = mktime();
socket_write($socket, $in, strlen($in));
socket_close($socket);
?>
...仅此而已 也许有一些更容易的通信(我需要每次都从 PHP 连接到 Android 设备,所以 PHP 不能等待来自 Android 的请求)。
感谢您的帮助。
【问题讨论】:
-
你可能会发现我之前发的这篇文章有一些用处:stackoverflow.com/questions/29159354/php-socket-with-android/…
标签: php android sockets serversocket