码迷,mamicode.com
首页 > 移动开发 > 详细

Android Socket与服务器通信通用Demo

时间:2014-09-25 23:48:48      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:android开发   socket   通信   网络   多线程   

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

以上。

Android Socket与服务器通信通用Demo

标签:android开发   socket   通信   网络   多线程   

原文地址:http://blog.csdn.net/eclipsexys/article/details/39551735

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!