[英]PHP (client) to Android (Server) Socket communication
我在使用telnet进行连接的android设备上制作了一个简单的ServerSocket应用程序,并且工作正常(发送的消息显示在logcat窗口中)。 问题:当我尝试从php页面建立连接时(我也在使用PHP套接字)。 Android套接字接受第一个连接,然后有些奇怪-有时他会读取从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的请求)。
感谢帮助。
您确实意识到您的Android ServerSocket应该维护一个“无限”循环,该循环等待传入的连接,通过读取请求直到到达流的末尾来处理一个请求,然后返回到等待另一个传入请求的状态。
改为执行以下操作:
public void start() throws IOException {
serverSocket = new ServerSocket(port);
running = true;
while(running) {
Socket connectionSocket = null;
InputStream input = null;
OutputStream output = null;
try {
connectionSocket = serverSocket.accept();
input = connectionSocket.getInputStream();
output = connectionSocket.getOutputStream();
// At this point do whatever you need to do with these streams
} catch(Exception e) {
throw new RuntimeException(e);
} finally {
if(input != null) {
input.close();
}
if(output != null) {
output.close();
}
if(connectionSocket != null) {
connectionSocket.close();
}
}
}
serverSocket.close();
serverSocket = null;
}
让此方法在单独的线程中运行,以免阻塞UI线程。 根据用户的请求或活动停止时,应将运行变量设置为false,以便服务器正常停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.