php android客户端,php服务端与android客户端socket通信

php写的服务端和java写的android客户端通过socket通信

php服务端的代码要在类似apache的服务器中运行,代码如下:

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

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);

socket_close($sock);

?>

android客户端在同一台机器上的模拟器中运行,代码如下:

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

import java.net.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(R.layout.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();

}

}

}

注:服务端的程序要先运行起来,然后运行客户端。这只是一个简单的socket通信。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值