安卓App和java通信实例
服务器:放在电脑上运行的java文件
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class MyServer implements Runnable{ //服务器连接 public static ServerSocket serverSocket; //连接 public static Socket socket; //端口 public static final int PORT = 8888; public void run() { DataInputStream dis = null; DataOutputStream dos = null; try { serverSocket = new ServerSocket(PORT); System.out.println("正在等待客户端连接..."); //这里处于等待状态,如果没有客户端连接,程序不会向下执行 while(true){ socket = serverSocket.accept(); dis = new DataInputStream(socket.getInputStream()); dos = new DataOutputStream(socket.getOutputStream()); //读取数据 String clientStr = dis.readUTF(); //写出数据 dos.writeUTF(clientStr); System.out.println("----客户端已成功连接!----"); //得到客户端的IP System.out.println("客户端的IP =" + socket.getInetAddress()); //得到客户端的端口号 System.out.println("客户端的端口号 =" + socket.getPort()); //得到本地端口号 System.out.println("本地服务器端口号=" + socket.getLocalPort()); System.out.println("-----------------------"); System.out.println("客户端:" + clientStr); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally {//我们把流的关闭写在finally里,即使读写出现问题,我们也能正常的关闭流! try { if (dis != null) dis.close(); if (dos != null) dos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args){ Thread desktopServerThread = new Thread(new MyServer()); desktopServerThread.start(); } }
App工程文件:
1、AndroidManifest.xml(主xml文件)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.himi" android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
2、res/values/strings.xml(资源文件)
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">这里输入文字发给服务器</string> <string name="app_name">SocketConnect</string> <string name="send">发送</string> <string name="get">这里显示服务器发来的信息!</string> </resources>
3、res/layout/main.xml(资源文件)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <EditText android:id="@+id/edit" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/Btn_commit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/send" /> <TextView android:layout_width="fill_parent" android:id="@+id/tv" android:layout_height="wrap_content" android:text="@string/get" /> </LinearLayout>
4、src/com.himi/MainActivity.java(Activity文件,客户端端主程序)
package com.himi; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * @author Himi */ public class MainActivity extends Activity implements OnClickListener { private Button btn_ok; private EditText edit; private TextView tv; //Socket用于连接服务器获取输入输出流 private Socket socket; //服务器server/IP地址 private final String ADDRESS = "10.203.8.167"; //服务器端口 private final int PORT = 8888; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); btn_ok = (Button) findViewById(R.id.Btn_commit); tv = (TextView) findViewById(R.id.tv); edit = (EditText) findViewById(R.id.edit); btn_ok.setOnClickListener(this); } public void onClick(View v) { if (v == btn_ok) { DataInputStream dis = null; DataOutputStream dos = null; try { //阻塞函数,正常连接后才会向下继续执行 socket = new Socket(ADDRESS, PORT); //socket = new Socket("localhost", PORT); dis = new DataInputStream(socket.getInputStream()); dos = new DataOutputStream(socket.getOutputStream()); //向服务器写数据 dos.writeUTF(edit.getText().toString()); String temp = "I say:"; temp += edit.getText().toString(); temp += "\n"; temp += "Server say:"; //读取服务器发来的数据 temp += dis.readUTF(); tv.setText(temp); } catch (IOException e) { Log.e("Himi", "Stream error!"); e.printStackTrace(); } finally { try { if (dis != null) dis.close(); if (dos != null) dos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }