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通信。