2009年8月26日 星期三

[Android]AndroidClinet與JavaServer TCP socket連線


之前一直在弄Android與java server的連線,
覺得明明Android API裡面有,
也是原來的java code
怎麼會不能跑呢?

先寫一隻用來測試socket的java server

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPDesktopServer implements Runnable {

public static final String SERVERIP = "220.131.10.187";
public static final int SERVERPORT = 12345;

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();
}
}




在寫一隻Android 手機Socket連線,
(From : http://www.androidres.com/?p=405  )



package com.AtestClient;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class AtestClient extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Socket socket;
try {
InetAddress serverAddr = InetAddress.getByName("220.131.10.187");

Log.d("TCP", "C: Connecting...");

try {
socket = new Socket(serverAddr, 12345);

String message = "AndroidRes,Where is my Pig (Android)?";
Log.d("TCP", "StringAfter");
try {
Log.d("TCP", "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(message);
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {

socket.close();
}

} catch (Exception e) {

}

} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}// TCPServer.SERVERIP

}
}



細微的修改網頁上的範例,
開啟了LogCat的功能,
去查找錯誤在哪裡。(開啟logcat http://blog.ben.idv.tw/2007/12/android-log.html ) 


測試server可以連線,
但是Clinet一直出現
unknow Socket error -1

 
在Google group 上發現解決方法
http://groups.google.com/group/android-developers/browse_thread/thread/28b416fafec6a84d?pli=1

原來這才是最重要的一步,
在AndroidManifest.xml檔案內加上 

 
 
Socket連線就建立成功了。

 

沒有留言:

張貼留言