2010年1月20日 星期三

Android Socket


呼~用了好幾個小時才完成

Client:



public class SocketTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Thread cThread = new Thread(new TCPClient());
cThread.start();
}
}

public class TCPClient implements Runnable {

public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("xxx.xxx.xxx.xxx");
//因為使用模擬器,所以必須填上host的IP位置,若用127.0.0.1會連不到,我猜可能是模擬器會連上模擬器的127.0.0.1了
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, 13267);
String message = "Hello from Client android emulator";
try {
Log.d("TCP", "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(message);
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
}

Server:

public class TCPDesktopServer implements Runnable {

public static final String SERVERIP = "127.0.0.1";
public static final int SERVERPORT = 13267;

public void run() {
try {
System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
while (true) {
Socket client = serverSocket.accept();
System.out.println("S: Receiving...");
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("S: Received: '" + str + "'");
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();

} finally {
//client.close();
System.out.println("S: Done.");
}
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}

public static void main(String a[]) {
Thread desktopServerThread = new Thread(new TCPDesktopServer());
desktopServerThread.start();
}
}