2011-07-27 9 views
1

Android 응용 프로그램에서 채팅 응용 프로그램을 구현하려고합니다. 클라이언트 (스마트 폰)는 컴퓨터에 설치된 서버를 통해 통신합니다. 클라이언트 - 서버 통신에 대해서는 잘 모릅니다. 그래서 당신의 도움이 절실히 필요합니다. 나는 많은 것을 읽었고 나는 HTTP (요청/응답)를 사용해야한다는 결론에 이르렀다. HTTP에서 클라이언트/서버가 요청을 보내고 서버/클라이언트가 응답을 각각 보냅니다. 이것이 작동하는 방식입니까? 소켓은 또 다른 방법의 임 플레멘 테이션입니다. HTTP를위한 소켓이 필요 없다는 뜻입니까? 미안하지만, 나는이 모든 것을 요구하고있다. 그러나 나는 정말로 혼란 스럽다. 제 3 자 소프트웨어가 필요합니까? 클라이언트 (안드로이드 응용 프로그램)와 서버 (Java 응용 프로그램)를 완전히 다른 프로젝트, 패키지에 넣었습니다. 또한 로그인 폼에 대해 다음 코드를 사용했다 :클라이언트 (Android 응용 프로그램) - 서버 (Java 응용 프로그램)

공공 무효 tryLogin() {

//The Android logging system provides a mechanism for collecting and viewing system debug output. Logcat dumps a log of system messages, which include things such as stack traces when the emulator throws an error and messages that you have written from your application by using the Log class. 
    Log.v(TAG, "Trying to Login");//TAG used to identify the source of a log message. It usually identifies the class or activity where the log call occurs./second param The message you would like logged. 
    EditText etxt_user = (EditText) findViewById(R.id.username);//finds the username TextView 
    EditText etxt_pass = (EditText) findViewById(R.id.password);//finds the pasword TextView 
    String username1 = etxt_user.getText().toString();//gets the text that the user has typed as his/her username 
    String password1 = etxt_pass.getText().toString();//gets the text that the user haw typed as his/her password 
    DefaultHttpClient client = new DefaultHttpClient();//creates a DefaultHttpClient object 
    HttpPost httppost = new HttpPost("http://......."); 
    //add your Data 
    List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>(); 
    nvps.add(new BasicNameValuePair("username", username1)); 
    nvps.add(new BasicNameValuePair("password", password1)); 

    try { 
      UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);//The message-body (if any) of an HTTP message is used to carry the entity-body associated with the request or response. The message-body differs from the entity-body only when a transfer-coding has been applied, as indicated by the Transfer-Encoding header field 
      httppost.setEntity(p_entity); 

      //Execute HTTP Post Request 
      HttpResponse response = client.execute(httppost); 
      Log.v(TAG, response.getStatusLine().toString());//HTTP/1.1 200 OK --> see DDMS //HTTP has been in use by the World-Wide Web global information initiative since 1990. This specification defines the protocol referred to as "HTTP/1.1", and is an update to RFC 2068 [33].//OK 200-->The request was fulfilled. 
      //The message-body (if any) of an HTTP message is used to carry the entity-body associated with the request or response. 
      HttpEntity responseEntity = response.getEntity(); 
      Log.v(TAG, "Set response to responseEntity" + EntityUtils.toString(responseEntity)); 

      //SAXParserFactory --> defines a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents. 
      SAXParserFactory spf = SAXParserFactory.newInstance();//obtain a new instance of a SAXParserFactory 
      SAXParser sp = spf.newSAXParser();//creates a new instance of a SAXParser using the currently configured factory parameters. 
      XMLReader xr = sp.getXMLReader();//interface for reading an xml document using callbacks 
      LoginHandler myLoginHandler = new LoginHandler(); 
      xr.setContentHandler(myLoginHandler); 
      xr.parse(retrieveInputStream(responseEntity));//retrieves the response of the server 

      ParsedLoginDataSet parsedLoginDataSet = myLoginHandler.getParsedLoginData(); 
      if (parsedLoginDataSet.getExtractedString().equals("SUCCESS")) { 
       // Store the username and password in SharedPreferences after the successful login 
       SharedPreferences.Editor editor=mPreferences.edit(); 
       editor.putString("UserName", username1); 
       editor.putString("PassWord", password1); 
       editor.commit(); 
       Message myMessage=new Message(); 
       myMessage.obj="SUCCESS"; 
       handler.sendMessage(myMessage); 
      } else if(parsedLoginDataSet.getExtractedString().equals("ERROR")) { 
       Intent intent = new Intent(getApplicationContext(), LoginError.class); 
       intent.putExtra("LoginMessage", parsedLoginDataSet.getMessage()); 
       startActivity(intent); 
       removeDialog(0); 
      } 
    } catch (Exception e) 
    { 
    /** InetAddress xxxx;//this code returns the localhost 
     try {//this code returns the localhost 
     xxxx = InetAddress.getLocalHost()to.String();*///this code returns the localhost 
      Intent intent = new Intent(getApplicationContext(), LoginError.class);//calls the activity LoginError.java 
      intent.putExtra("LoginMessage", "Unable to login");//sends information with intent.putExtra. The information that will be sent is the text which we would like to appear in the TextView of the LoginError activity.(putextra(name, value????)) 
      startActivity(intent);//starts the LoginError.java activity. 
      removeDialog(0);//closes the dialog box with the message "please wait while connecting... 
      // e.printStackTrace();//It's a method of the Throwable class. All exceptions are a subclass of that class. The trace prints exactly where the program was at the moment the exception was throw. 
    /**} catch (UnknownHostException e1) {//this code returns the localhost 
     e1.printStackTrace();//this code returns the localhost 
    }*///this code returns the localhost 

     } 

}

는 라인 xr.setContentHandler (myLoginHandler)까지 작동하는 것 같다

; 나머지 코드는 서버를 구축해야합니다. 서버가 클라이언트로부터 요청을 받고 응답을 다시 보내는 방법은 무엇입니까? 또한 HTTPpost에서 내가 놓아야 할 주소는 무엇입니까? 내 IP 주소를 넣을 때 작동하지 않지만 기본 geteway를 사용하면 작동하는 것 같습니다. 적어도, 동일한 컴퓨터에 클라이언트와 서버를 가지고 통신을 테스트 할 수 있습니까? 아니면 두 대의 컴퓨터가 있어야합니다 (하나는 클라이언트 용이고 다른 하나는 서버 용). 많은 질문이 있습니다. 그러나 제발 그들 중 일부는 저에게 답을주십시오. 나는 정말로 초보자이다.

미리 감사드립니다.

답변

0

REST 서비스를 살펴 보는 것이 좋습니다. 기본 구조는 서버에 안드로이드 애플 리케이션 HTTP 요청을 (별도 스레드에서) 선호하고 서버가 xml 또는 json으로 응답하도록하는 것입니다.

자주 사용하는 스레드 된 http 게시 클래스입니다.

import java.util.ArrayList; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.params.BasicHttpParams; 
import org.apache.http.params.HttpConnectionParams; 
import org.apache.http.params.HttpParams; 
import org.apache.http.util.EntityUtils; 
import android.os.Handler; 
import android.os.Message; 

public class HttpPostThread extends Thread { 
    public static final int FAILURE = 0; 
    public static final int SUCCESS = 1; 
    public static final String VKEY = "FINDURB#V0"; 

    private final Handler handler; 
    private String url; 
    ArrayList<NameValuePair> pairs; 
public HttpPostThread(String Url, ArrayList<NameValuePair> pairs, final Handler handler) 
{ 
this.url =Url; 
    this.handler = handler; 
    this.pairs = pairs; 
    if(pairs==null){ 
     this.pairs = new ArrayList<NameValuePair>(); 
    } 
} 


@Override 
public void run() 
{ 
try { 

HttpClient client = new DefaultHttpClient(); 
HttpPost post = new HttpPost(url); 
HttpParams httpParameters = new BasicHttpParams(); 
int timeoutConnection = 3000; 
HttpConnectionParams.setConnectionTimeout(httpParameters, 
     timeoutConnection); 
if(pairs!=null) 
    post.setEntity(new UrlEncodedFormEntity(pairs)); 
    HttpResponse response = client.execute(post); 
    HttpEntity entity = response.getEntity(); 
    String answer = EntityUtils.toString(entity); 
    Message message = new Message(); 
      message.obj = answer; 
      message.what = HttpPostThread.SUCCESS; 
      handler.sendMessage(message); 


} catch (Exception e) { 
    e.printStackTrace(); 
    handler.sendEmptyMessage(HttpPostThread.FAILURE); 
} 

} 
} 

서버와 통신해야 할 때마다 이와 같은 작업을 수행해야합니다.

Handler handler = new Handler() 
    { 
     @Override 
     public void handleMessage(Message msg) 
     { 
      removeDialog(0); 
      switch (msg.what) 
      { 
      case HttpPostThread.SUCCESS: 
       String answer = (String)msg.obj; 
       if (answer != null) 
       { 
       //do something with the return string 
       } 
       break; 

       case HttpPostThread.FAILURE: 
       // do some error handeling 
       break; 

       default: 
       break; 
      } 
     } 
} 
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>(); 
pairs.add(new BasicNameValuePair("key", "value")); 
HttpPostThread thread = new HttpPostThread("http://serviceURL",pairs, handler); 
thread.start(); 

아래에서 질문에 대한 답변을 얻으려면 다양한 기술로 서비스를 구현할 수 있습니다. 아래는 위의 예제에서 키/값 쌍을 얻는 PHP 서비스의 간단한 예입니다. 간단한 PHP 서비스

<?php 
    $value = $_POST['key']; 
    echo "The value".$value. "was received by the service!"; 
    ?> 

서버 handleMessage 호출할지 응답과 답변의 내부 값

예 행을 같게한다

echo "The value".$value. "was received by the service!"; 
관련 문제