我想在android中實現聊天應用程序。客戶端(智能手機)將通過安裝在計算機中的服務器進行通信。我不知道客戶端 - 服務器通信,所以我絕望地需要你的幫助。我已經閱讀了很多關於我的結論,我必須使用HTTP(請求/響應),這是正確的嗎?在HTTP中,客戶端/服務器發送請求,服務器/客戶端分別發送響應,這是它的工作方式嗎?套接字是另一種方式的阻礙,我的意思是我不需要HTTP的任何套接字?對不起,我要求所有這些,但我真的很困惑。我是否也需要任何第三方軟件?我已經將客戶端(android應用程序)和服務器(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它似乎工作。至少,我可以讓客戶端和服務器在同一臺計算機上測試通信,或者我必須有兩臺計算機(一個用於客戶端,另一個用於服務器)? 我知道很多問題,但請至少在其中的一些回答我。我真的是一個新手。
預先感謝您!