Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android Socket與服務器通信通用Demo

Android Socket與服務器通信通用Demo

編輯:關於Android編程

在Android中通過Socket來來連接服務器,是一種比較簡單的網絡連接方式,雖然現在使用的不多,但某些場合還是很方便的,這裡總結一下基本的寫法。

客戶端:

try {
				Socket socket = new Socket(host, port);
				socket.setSoTimeout(6 * 1000);
				PrintWriter printWriter = new PrintWriter(
						socket.getOutputStream(), true);
				printWriter.println("socket test");
				printWriter.flush();

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(socket.getInputStream(), "GBK"));
				revMsg = reader.readLine();
				if (TextUtils.isEmpty(revMsg)) {
					revMsg = "Server Error";
				}
				printWriter.close();
				reader.close();
				socket.close();
				return revMsg;
			} catch (Exception e) {
				e.printStackTrace();
				revMsg = "Server Error";
			}

服務器端:

import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	public static void main(String[] args) {
		try {
			ServerSocket serverSocket = new ServerSocket(8888);
			while (true) {
				Socket socket = serverSocket.accept();
				new ServerThread(socket);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

class ServerThread extends Thread {

	private Socket socket;
	private BufferedReader bufferedReader;
	private PrintWriter printWriter;

	public ServerThread(Socket socket) throws IOException {
		this.socket = socket;
		bufferedReader = new BufferedReader(new InputStreamReader(
				socket.getInputStream()));

		printWriter = new PrintWriter(socket.getOutputStream(), true);
		System.out.println("Client(" + getName() + ") connected...");

		start();
	}

	@Override
	public void run() {
		try {
			String line = bufferedReader.readLine();

			if (!line.equals("exit")) {
				System.out.println("Client(" + getName() + ") say: " + line);
				WriteToTxt(line + "\r\n","/local/data.txt");
				printWriter.println("Receive Success!");
			}
			printWriter.close();
			bufferedReader.close();
			socket.close();
		} catch (IOException e) {
		}
	}

	private void WriteToTxt(String str, String path) {
		try {
			FileWriter writer = new FileWriter(path, true);
			writer.write(str);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

服務器端通過多線程來處理多個並發的socket請求。

Demo很簡單。

以上。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved