注:php作为服务端, android作为客户端
Php服务端:
<?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)."<br>";
}
//绑定到socket端口
if(($ret=socket_bind($sock,$address,$port))<0)
{
echo "socket_bind()失败的原因是:".socket_strerror($ret)."<br>";
}
//开始监听
if(($ret=socket_listen($sock,4))<0)
{
echo "socket_listen()失败的原因是:".socket_strerror($ret)."<br>";
}
do {
if (($msgsock = socket_accept($sock)) < 0)
{
echo "socket_accept() failed: reason: ". socket_strerror($msgsock) . "/n";
echo "/nThe Server is Stop……/n";
break;
}
//发到客户端
$msg ="<font color=red>Welcome ToServer!</font><br>";
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 java.net.Socket;
importjava.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class SocketTestextends Activity {
/** Called when the activity is firstcreated. */
@Override
public void onCreate(BundlesavedInstanceState) {
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();
}
}
}