php与Android客户端通信

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Php与Android socket通信

注:php作为服务端, android作为客户端

Php服务端:

//确保在连接客户端时不会超时

set_time_limit(0);

//设置IP和端口号

$address='127.0.0.1';

$port=3333; //调试的时候,可以多换端口来测试程序!

//创建一个SOCKET

if(($sock=socket_create(AF_INET,SOCK_STREAM,SOL_TCP))<0)

{

echo "socket_create() 失败的原因是:".socket_strerror($sock)."
"; }

//绑定到socket端口

if(($ret=socket_bind($sock,$address,$port))<0)

{

echo "socket_bind() 失败的原因是:".socket_strerror($ret)."
";

}

//开始监听

if(($ret=socket_listen($sock,4))<0)

{

echo "socket_listen() 失败的原因是:".socket_strerror($ret)."
"; }

do {

if (($msgsock = socket_accept($sock)) < 0)

{

echo "socket_accept() failed: reason: " .

socket_strerror($msgsock) . "/n";

echo "/nThe Server is Stop……/n";

break;

}

//发到客户端

$msg ="Welcome To Server!
";

socket_write($msgsock, $msg, strlen($msg));

socket_close($msgsock);

echo "/nThe Server is running……/n";

printf("/nThe Server is running……/n");

} while (true);

printf("========出来了……/n");

socket_close($sock);

?>

Android客户端:

package com.msi.getwebpage;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import .Socket;

import .UnknownHostException;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

public class SocketTest extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(yout.main);

try {

System.out.println("准备连接");

Socket socket = new Socket("10.0.2.2", 3333);

System.out.println("连接上了");

Intent intent = new Intent();

intent.setClass(SocketTest.this, ConnectActivity.class);

SocketTest.this.startActivity(intent);

InputStream inputStream = socket.getInputStream();

byte buffer[] = new byte[1024*4];

int temp = 0;

String res = null;

//从inputstream中读取客户端所发送的数据

System.out.println("接收到服务器的信息是:");

while ((temp = inputStream.read(buffer)) != -1){

System.out.println(new String(buffer, 0, temp));

res += new String(buffer, 0, temp);

}

System.out.println("已经结束接收信息……");

socket.close();

inputStream.close();

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

相关文档
最新文档