Android Socket与服务器通信通用Demo

在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很简单。

以上。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。