第一步:实现socket通信。
首先学习下socket编程,这是最基本的。
我们利用PC上编写一个Java程序为服务器,再编写一个Android app作为客户端,然后实现通信。
新建一个Java类如下:
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServer {
public static void main(String[] args) throws IOException
{
ServerSocket ss = new ServerSocket(30000);
while (true) {
Socket socket = ss.accept();
OutputStream os = socket.getOutputStream();
os.write("my email is ruihanL@126.com".getBytes("utf-8"));
os.close();
socket.close();
}
}
}
点击运行,假如出现异常,应该就是端口被占用,打开任务管理器,把javaw.exe终止掉后重新点击运行。
andriod app代码如下:
package com.example.simpleclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView1);
new Thread(){
public void run(){
try{
Socket socket = new Socket("192.168.10.103",30000);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = br.readLine();
textView.setText(line);
br.close();
socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
里面的IP地址改为PC电脑所在的IP,端口必须一样。编译后安装到手机上。布局文件仅是一个textview而已。
运行app,就可以看到”my email is ruihanL@126.com”了。
原文地址:http://blog.csdn.net/shendan00/article/details/44001291