算是做一個筆記吧。以免以後忘記了。
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import android.util.Log;

public class ServerSocketMethod {
	static boolean isrun = true;
	static String TAG = "ServerSocketMethod";
	static byte[] buffer = null;

	// 將組裝好的資料進行Scoket上傳和接受返回
	//@SuppressWarnings("resource")
	public static byte[] ServerSocketUpload(int Port, String IP,
			byte[] sendbytes) {

		Log.e(TAG, "Port+IP" + Port + IP);
		Socket socket;
		InetSocketAddress isa;
		try {
			// 上傳
			Log.e(TAG, "上傳開始");
			socket = new Socket();
			isa = new InetSocketAddress(IP, Port);
			// 建立socket物件,指定伺服器端地址和埠號
			Log.e(TAG, "上傳1");
			socket.connect(isa, 5000);// 設定5秒超時
			OutputStream out = socket.getOutputStream();// 建立一個輸出流物件
			Log.e(TAG, "上傳2");
			out.write(sendbytes); // 要輸出給移動伺服器的內容..
			Log.e(TAG, "上傳3");
			out.close();
			out.flush();
			socket.close();

			// 接受返回
			ServerSocket tcpSocket = null;
			tcpSocket = new ServerSocket(Port);
			Socket s = null;
			Log.e(TAG, "返回了1");
			
			s = tcpSocket.accept();// 如果未收到資料,此句不會繼續向下執行,一直處於監聽狀態
			s.setSoTimeout(5000);//設定接收5秒超時
			Log.e(TAG, "返回了2");
			InputStream in = s.getInputStream();
			Log.e(TAG, "返回了3");
			byte[] buffer = new byte[86];
			in.read(buffer);
			String DRb = new String(buffer, 0, 2);
			Log.e(TAG, "DRb:" + DRb);
			Log.e(TAG, "buffer:" + buffer);
			Log.e(TAG, "返回buffer");
			s.close();
			tcpSocket.close();
			return buffer;

		} catch (UnknownHostException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

	}
}