1. 程式人生 > >使用Eclipse搭建簡易Android伺服器

使用Eclipse搭建簡易Android伺服器

         一直都想做一些自己的app奈何多數功能都需要藉助於伺服器才能實現,本想用第三方平臺,細想之下畢竟不是長久之計。這裡自己搭建一個Android簡易伺服器

         這篇文章只是簡單介紹下如何使用Java搭建Android伺服器,剛學習不久,有不足之處歡迎指出,共同進步!

        一、環境搭建

                  1、  所需軟體列表

                                   a、 Tomcat

                                   b、Eclipse

                                   c、JDK

                  2、環境配置

      二、專案配置

                 1、服務端

                        1.1     Eclipse中 File-->new--->Dynamic Web Project 新建一個Web Project

                         1.2     在Java Resources 下新建一個包和Main類,寫入如下程式碼: 

package com.chatfree.server;
import java.io.BufferedReader;
import 
java.io.DataInputStream; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class Main { public static final int PORT = 8888;//監聽的埠號 public static void main(String[] args) { System.out.println("伺服器啟動...\n"); Main server = new
Main(); server.init(); } public void init() { try { ServerSocket serverSocket = new ServerSocket(PORT); while (true) { // 一旦有堵塞, 則表示伺服器與客戶端獲得了連線 Socket client = serverSocket.accept(); // 處理這次連線 new HandlerThread(client); } } catch (Exception e) { System.out.println("伺服器異常: " + e.getMessage()); } } private class HandlerThread implements Runnable { private Socket socket; public HandlerThread(Socket client) { socket = client; new Thread(this).start(); } public void run() { try { // 讀取客戶端資料 DataInputStream input = new DataInputStream(socket.getInputStream()); String clientInputStr = input.readUTF();//這裡要注意和客戶端輸出流的寫方法對應,否則會拋 EOFException // 處理客戶端資料 System.out.println("客戶端發過來的內容:" + clientInputStr); // 向客戶端回覆資訊 DataOutputStream out = new DataOutputStream(socket.getOutputStream()); System.out.print("請輸入:\t"); // 傳送鍵盤輸入的一行 String s = new BufferedReader(new InputStreamReader(System.in)).readLine(); out.writeUTF(s); out.close(); input.close(); } catch (Exception e) { System.out.println("伺服器 run 異常: " + e.getMessage()); } finally { if (socket != null) { try { socket.close(); } catch (Exception e) { socket = null; System.out.println("服務端 finally 異常:" + e.getMessage()); } } } } } }

                  1.3 在第一步環境配置中配置好Tomcat後,點選Eclipse中的Tomcat圖示,執行Tomcat

                   1.4  在Main類上右鍵  Run as-->Java Application 服務即可執行

                2、服務端      

                      新建一個Android專案,在MainActivity中寫入以下程式碼,注意修改你的IP的地址:

package com.example.zgp.chatfree;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends ActionBarActivity {
    private TextView myTextView;
    private Button mBtnConnect;
@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTextView = (TextView) findViewById(R.id.tv_info);
mBtnConnect=(Button)findViewById(R.id.btn_connect);
mBtnConnect.setOnClickListener(new View.OnClickListener() {
            @Override
public void onClick(View v) {

                new Thread(new Runnable() {
                    @Override
public void run() {

                            Socket socket = null;
                            try {
                                //建立一個流套接字並將其連線到指定主機上的指定埠號
socket = new Socket("192.168.1.91", 8888);
//讀取伺服器端資料
DataInputStream input = new DataInputStream(socket.getInputStream());
//向伺服器端傳送資料
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
String str = "I am Client";
out.writeUTF(str);
                                final String ret = input.readUTF();
runOnUiThread(new Runnable() {
                                    @Override
public void run() {
                                        myTextView.setText(ret);
Toast.makeText(MainActivity.this,ret,Toast.LENGTH_SHORT).show();
}
                                });
System.out.println("伺服器端返回過來的是: " + ret);
out.close();
input.close();
} catch (Exception e) {
                                System.out.println("客戶端異常:" + e.getMessage());
} finally {
                                if (socket != null) {
                                    try {
                                        socket.close();
} catch (IOException e) {
                                        socket = null;
System.out.println("客戶端 finally 異常:" + e.getMessage());
}
                                }
                            }
                        }

                }).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.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
            return true;
}

        return super.onOptionsItemSelected(item);
}
}
      佈局檔案如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    <TextView
android:id="@+id/tv_info"
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
   <Button
android:layout_below="@+id/tv_info"
android:text="Connect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_connect"/>
</RelativeLayout>

             執行Android專案,點選上面的Button,Eclipse 服務端控制檯即可看到輸出,同是在控制檯輸入字元,即可看到app中文字框中的內容改變。