Android (내 Java 프로그램)에 TCP 클라이언트가 있습니다. 서버는 이클립스에서 실행되는 또 다른 자바 애플리케이션이었다. 이 상황에서는 모든 것이 잘 작동합니다.휴대폰의 Android TCP 클라이언트가 외부 서버와 통신하는 데 문제가 있습니다.
내 동료의 앱 (Rhapsody에서 개발되었고 C++로 개발 됨)에서 메시지를 수신하려고하면 앱이 종료되고 메시지가 전송되는 동안에는 메시지가 수신되지 않습니다. 왜 이런 일이 일어나는 지 아십니까?
시간과 노력에 감사드립니다.
건배, 마두
자바 서버는 다음과 같이이다 :
public class TCPSendServer implements Runnable{
public static final String SERVERIP = "192.168.178.24";
public static final int SERVERPORT = 1200;
//static Category cat = Category.getInstance(TCPSendServer.class.getName());
//cat.debug("Start of main()");
public void run() {
try {
System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
String msg = "<MSG><N>shiftDirection</N><V>1</V></MSG>";
String msg1 = "<MSG><N>vehicleSpeed</N><V>120</V></MSG>";
String msg2 = "SD<!N><V>0<!V><!MSG>";
//while (true) {
Socket client = serverSocket.accept();
try {
System.out.println("S: Sending: '" + msg + "'");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);
Thread.sleep (5000);
out.println(msg);
Thread.sleep (5000);
//out.println(msg2);
Thread.sleep (5000);
out.println(msg1);
//out.flush();
System.out.println("S: Sent.");
System.out.println("S: Done.");
} catch(Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} //finally {
// client.close();
//}
//}
} catch (Exception e) {
System.out.println("S: First try error");
e.printStackTrace();
}
}
public static void main (String a[]) {
Thread desktopServerThread = new Thread(new TCPSendServer());
desktopServerThread.start();
}
}
안드로이드 클라이언트 코드 : 주요 활동 :
public class TCPListen extends Activity implements TCPListener {
private TextView mTitle;
public String data[] = new String[2];
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);
//TcpServiceHandler handler=new TcpServiceHandler(this);
//handler.execute("192.168.178.24");
TcpServiceHandler handler = new TcpServiceHandler(this,this);
Thread th = new Thread(handler);
th.start();
}
public String[] callCompleted(String source){
Log.d("TCP", "Std parser " + source);
mTitle.setText(source);
//String data[] = new String[2];
//if (source.matches("<MSG><N>.*</N><V>.*</V></MSG>")) {
Document doc = null;
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = (Document) db.parse(new ByteArrayInputStream(source.getBytes()));
NodeList n = doc.getElementsByTagName("N");
Node nd = n.item(0);
String msgName = nd.getFirstChild().getNodeValue();
NodeList n1 = doc.getElementsByTagName("V");
Node nd1 = n1.item(0);
String tmpVal = nd1.getFirstChild().getNodeValue();
data[0] = msgName;
data[1] = tmpVal;
Log.d("TCP", "Inside Std parser " + data[0] + " " + data[1]);
//actionOnData(data[0], data[1]);
}
catch(Exception e){
e.printStackTrace();
}
Log.d("TCP", "Just outside Std parser " + data[0] + " " + data[1]);
return data;
//} else Log.d("TCP", "Message in wrong format " + source);
//mTitle.setText("Message in wrong format " + source);
//return data;
}
인터페이스 :
public interface TCPListener {
public String[] callCompleted(String msg);
}
TCPServiceHandler는 :
public class TcpServiceHandler implements Runnable {
TCPListener _listener;
private Activity _act;
public TcpServiceHandler(TCPListener listener, Activity act){
_listener = listener;
_act = act;
}
public synchronized void run() {
// TODO Auto-generated method stub
//if(socket==null){
try {
InetAddress serverAddr = InetAddress.getByName("192.168.178.25");
Socket socket = new Socket(serverAddr, 1200);
//
while(true){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final String str = in.readLine();
this._act.runOnUiThread(new Runnable(){
public void run() {
_listener.callCompleted(str);
}
});
}
catch(Exception e){
e.printStackTrace();
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Android 코드 (HTC Desire)에서 클라이언트 코드를 실행합니다. 서버가 Eclipse에서 실행중인 Java 앱인 경우 Android 서버에서이 서버가 보낸 데이터를받을 수 있습니다. 다른 앱 (서버로 작동하는 것으로 간주 될 수있는 abc)에서 데이터를 수신하려고하면 앱에 연결할 수 있지만 데이터를 수신 할 수 없습니다. 실제 전화를 abc에 연결하는 대신 클라이언트를 에뮬레이터에서 연결하려고하면 abc가 닫힌 후에 만 데이터를받을 수 있습니다. abc가 닫히고 데이터가 전송되고 데이터를 보낼 때가 아닙니다. 실제 휴대 전화 및 abc가 작동하지 않음 연결이 설정되었지만 데이터가 없음 –
답변 해 주셔서 감사합니다. 네트워크 리다이렉션과 포트 포워딩에 대해 자세히 설명해 주시겠습니까? 안드로이드에서 서버를 실행할 때 포트 포워딩을 사용했습니다. 예 : adb forward tcp : 6100 tcp : 7100). 또한 내 안드로이드 전화를 외부 서버가 연결된 것과 동일한 WLAN에 연결합니다. 또한 네트워크의 일부인 Android 폰 (내가 추측하는 것)을 만드는 것에 대해 설명하면 도움이됩니다. –