I want to build an Http Server which will serve the requests of a chat application in android. Because i am really confused… in my code I have to use sockets? How can i make the client to communicate with the server? Which is the code i have to add in the server in order to accept the requests from the client and respond to them? The code I use in the client is the following:
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:80");
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);
httppost.setEntity(p_entity);
//Execute HTTP Post Request
HttpResponse response = client.execute(httppost);
Log.v(TAG,"something");
Log.v(TAG, response.getStatusLine().toString());
HttpEntity responseEntity = response.getEntity();
Please I really need an answer. Thank you!!!
Sockets (Socket for client, ServerSocket for server) is the most basic layer of communication. You chose TCP or UDP and over it, you need to encode all of your protocol.
There are also some libraries that encode higher level protocols (HTTP, FTP, and even higher as SOAP). If you use these libraries, you usually do not need to manage socket as it is done by the library itself (in the server you only specify port and optionally IP to bind to; in the client you specify host and port to connect to).
You can use different combinations (v.g. implementing your server with SOAP and then creating and sending a SOAP message from the client using Socket) but the simplest way is to use the same library both for the server and client.
About which one is better: it depends of what you want it to. Higher level libraries are more flexible but may take a time to master and may have more overhead, lower level needs that you manage everything. If there is no more compelling reason, I usually just use the HTTP protocol (both from the JVM or from the Apache Foundation projects).