簡單的Android客戶端和服務端socket通訊

今天是入職第一天,老大知道我以前沒有接觸過socket,而公司用socket比較多,因此下午讓我嘗試寫一下Android客戶端和server基於TCP Socket通訊java

 

大概就是一個Android客戶端,向服務器發送用戶密碼,服務端驗證,返回json格式數據。android

客戶端:

  • MainActivity代碼:
package com.boke.socketclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	public EditText et_username, et_password;
	public TextView tv_result;
	public Button btn_login;
	public Socket socket = null;
	public String buffer = "";
	public Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 0x11) {
				Bundle bundle = msg.getData();
				String result = bundle.getString("msg");
				tv_result.setText(result);
				JSONObject resultJson;
				try {
					resultJson = new JSONObject(result);
					Toast.makeText(MainActivity.this,
							resultJson.getString("msg"), Toast.LENGTH_SHORT)
							.show();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
	}

	/**
	 * 初始化控件
	 */
	private void init() {
		et_username = (EditText) findViewById(R.id.et_username);
		et_password = (EditText) findViewById(R.id.et_password);
		tv_result = (TextView) findViewById(R.id.tv_result);
		btn_login = (Button) findViewById(R.id.btn_login);
		// 設置監聽事件
		btn_login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				login();
			}

		});

	}

	/**
	 * 登陸
	 */
	private void login() {
		String username = et_username.getText().toString();
		String password = et_password.getText().toString();
		JSONObject data = new JSONObject();
		try {
			data.put("username", username);
			data.put("password", password);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		new MyThread(data).start();

	}

	class MyThread extends Thread {
		public JSONObject data;

		public MyThread(JSONObject data) {
			this.data = data;
		}

		@Override
		public void run() {
			// 定義消息
			Message msg = new Message();
			msg.what = 0x11;
			Bundle bundle = new Bundle();
			bundle.clear();
			OutputStream ou = null;
			InputStream in = null;
			BufferedReader bff = null;
			try {
				// 鏈接服務器 並設置鏈接超時爲5秒
				socket = new Socket();
				socket.connect(new InetSocketAddress("10.0.2.2", 30000), 5000);// 模擬器與本機通訊地址
                //若是是eclipse自帶模擬器用這個地址,若是是genymotion的話使用10.0.3.2。
				// 獲取輸入輸出流
				ou = socket.getOutputStream();
				in = socket.getInputStream();
				// 向服務器發送信息
				Log.v("TAG", "TAG--向服務器發送的消息爲:" + data.toString());
				ou.write(data.toString().getBytes("gbk"));
				ou.flush();
				socket.shutdownOutput();
				bff = new BufferedReader(new InputStreamReader(in));
				// 讀取發來服務器信息
				String line = "";
				buffer = "";
				while ((line = bff.readLine()) != null) {
					buffer = line + buffer;
				}
				Log.v("TAG", "TAG--服務器的返回爲:" + buffer);
				bundle.putString("msg", buffer.toString());
				msg.setData(bundle);
				// 發送消息 修改UI線程中的組件
				myHandler.sendMessage(msg);
			} catch (SocketTimeoutException aa) {
				// 鏈接超時 在UI界面顯示消息
				bundle.putString("msg", "服務器鏈接失敗!請檢查網絡是否打開");
				msg.setData(bundle);
				// 發送消息 修改UI線程中的組件
				myHandler.sendMessage(msg);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				// 關閉輸入輸出流
				try {
					// 關閉各類輸入輸出流
					bff.close();
					ou.close();
					in.close();
					socket.close();// socket最後關閉
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
  • activity_main.xml佈局文件:
<LinearLayout 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:orientation="vertical"
    android:padding="16dp"
    tools:context="${relativePackage}.${activityClass}" >

    <EditText
        android:id="@+id/et_username"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="16dp"
        android:hint="請輸入用戶名" />

    <EditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="16dp"
        android:hint="請輸入密碼"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btn_login"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="16dp"
        android:text="登陸" />

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@string/hello_world" />

</LinearLayout>
  • AndroidManifest.xml中記得添加權限:
<uses-permission android:name="android.permission.INTERNET"/>

服務端:

  • SoketServer.java代碼:
package com.boke.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SoketServer {
	/**
	 * 程序入口
	 * 
	 * @param args
	 */
	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = new ServerSocket(30000);
		System.out.println("等待客戶端連入...");
		while(true){
			//等待客戶端連入
			Socket socket = serverSocket.accept();
			new Thread(new AndroidRunnable(socket)).start();
		}
	}
}
  • AndroidRunnable.java代碼:
package com.boke.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

import net.sf.json.JSONObject;

public class AndroidRunnable implements Runnable {
	public Socket socket = null;

	public AndroidRunnable(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		System.out.println("客戶端連入成功...");
		String line = "";
		InputStream input = null;
		OutputStream output = null;
		BufferedReader bff = null;
		JSONObject result = new JSONObject();// 須要導入json的多個jar包,http://download.csdn.net/detail/u011381488/6457097
		try {
			// 向客戶端發送信息
			output = socket.getOutputStream();
			input = socket.getInputStream();
			bff = new BufferedReader(new InputStreamReader(input));

			// 獲取客戶端的信息
			while ((line = bff.readLine()) != null) {
				System.out.println("接收到客戶端的消息爲:" + line);
				socket.shutdownInput();// 半閉socket
				// 向客戶端發送消息
				JSONObject jsonObject = JSONObject.fromObject(line);
				String username = jsonObject.getString("username");
				String password = jsonObject.getString("password");
				// 驗證用戶名、密碼
				if (username.equals("123") && password.equals("456")) {
					result.put("state", "0");
					result.put("msg", "登陸成功");
				} else {
					result.put("state", "1");
					result.put("msg", "密碼錯誤");
				}
				System.out.println("向客戶端發送的消息爲:" + result.toString());
				OutputStream out = socket.getOutputStream();
				out.write(result.toString().getBytes());
				out.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 關閉輸入輸出流
			try {
				output.close();
				bff.close();
				input.close();
				socket.close();// socket最後關閉
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

運行效果:

  • 學習纔剛開始,但願能堅持,多理解,加油!
相關文章
相關標籤/搜索