I coded an application in Java for my Android phone that uses a socket connetion to send and recieve text data which works nicely, it uses PrintWriter
and BufferedReader
Alot was said in the process about using HTTP connection. I am hoping to take this ip开发者_开发问答portunity to establish where HTTP would differ from Sockets so I hope you can help me with the following.
1) I create a socket connection using the following
Server Side:
serverSocket = new ServerSocket(4444);
Client Side:
clientSocket = new Socket(address, portNumber);
So What would be the HTTP equivalent on the client and server sides?
2) To send data from the client to the server I do the following:
pw = new PrintWriter(clientSocket.getOutputStream(),true);
pw.write(AStringVariableInThisCase+"\n");
pw.flush();
What would be the correct manner within an HTTP Connection?
3) To recieve the data sent from the client, on the server side I do the following:
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String language = br.readLine();
What would be the equivalent using an HTTP Connection?
The program I have designed allows data to be passed back and forth with the server using its own set of classes and continues to do so using the PrintWriter and BuferedReader to do so.
Thanks for any help you can contribute with distinguishing the differences.
HTTP is a protocol. It's (generally) used over a socket.
Java provides the HttpUrlConnection class for a convenient way of using HTTP over a socket.
The main difference is that HTTP is structured as a transaction rather than as a connection. The client side of the transaction has to supply headers with particular format and information, and the reply will begin with some header lines. HTTP typically closes the connection after one transaction is complete.
精彩评论