Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
客户端(Android应用程序)-服务器(Java应用程序)_Android - Fatal编程技术网

客户端(Android应用程序)-服务器(Java应用程序)

客户端(Android应用程序)-服务器(Java应用程序),android,Android,我正在尝试在android中实现一个聊天应用程序。客户端智能手机将通过安装在计算机中的服务器进行通信。我不知道客户机与服务器之间的通信,所以我迫切需要您的帮助。我已经读了很多关于HTTPrequest/response的文章,我得出的结论是我必须使用HTTPrequest/response,对吗?在HTTP中,客户端/服务器分别发送请求和服务器/客户端发送响应,这是它的工作方式吗?套接字是另一种实现方式,我的意思是HTTP不需要任何套接字?对不起,我问了所有这些问题,但我真的很困惑。我还需要任何

我正在尝试在android中实现一个聊天应用程序。客户端智能手机将通过安装在计算机中的服务器进行通信。我不知道客户机与服务器之间的通信,所以我迫切需要您的帮助。我已经读了很多关于HTTPrequest/response的文章,我得出的结论是我必须使用HTTPrequest/response,对吗?在HTTP中,客户端/服务器分别发送请求和服务器/客户端发送响应,这是它的工作方式吗?套接字是另一种实现方式,我的意思是HTTP不需要任何套接字?对不起,我问了所有这些问题,但我真的很困惑。我还需要任何第三方软件吗?我将clientandroid应用程序和serverjava应用程序放在完全不同的项目和包中。我还将以下代码用于登录表单:

公共无效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.setContentHandlermyLoginHandler行;对于其余的代码,我必须构建服务器。服务器如何从客户端获取请求,然后将响应发送回客户端?同样在HTTPpost中,我必须输入哪个地址?当我输入ip地址时,它不起作用,但当我使用默认的Getway时,它似乎起作用。至少,我可以让客户端和服务器在同一台计算机上测试通信,或者我必须有两台计算机,一台用于客户端,一台用于服务器? 我知道有很多问题,但请至少回答我其中的一些问题。我真的是个新手


提前谢谢你

我建议您考虑一下REST服务。基本结构是让android应用程序在服务器的单独线程中优先执行HTTP请求,并让服务器用xml或json响应

这里有一个我经常使用的线程化http post类

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
    $value = $_POST['key'];
    echo "The value".$value. "was received by the service!";
    ?>
  echo "The value".$value. "was received by the service!";