A secret class in Java socket programming

Source: Internet
Author: User
Programming Java platform in the java.net package to implement the socket. In this article, we will work with the following three classes in the java.net package: · URLConnection Socket  ServerSocket contains more classes in the java.net package, but these are the things that you most often encounter, let's start with URLConnection, which provides a way to use sockets in your Java code without knowing the underlying mechanism of the socket. You can use sockets to connect to a URL without even trying. The following steps are included: • Create a urlconnection configure it with different setter methods • Connect to URLConnection interact with different getter methods.  Some examples demonstrate how to use URLConnection to request a document from a single server. Urlclient class We'll start with the structure of the Urlclient class. Import java.io.*;
Import java.net.*;
public class Urlclient {
protected URLConnection Connection;
public static void Main (string[] args) {}
public string Getdocumentat (String urlstring) {}
Note: You must import the java.net and java.io packages first. We give our class an instance variable for saving a URLConnection our class contains a main () method that handles the logical flow of browsing a document (logic flows),  Our class also contains the Getdocumentat () method for connecting to the server and requesting the document, and we'll explore the details of these methods below. Browse the document the main () method is used to process the logical stream (logic flow) that browses a document: public static void Main (string[] args) {
Urlclient client = new Urlclient ();
String Yahoo = client.getdocumentat ("http://www.yahoo.com");
System.out.println (Yahoo);
Our main () method simply creates a new instance of the Urlclient class and uses a valid URL string to invoke the Getdocumentat () method. When the call returns the document, we store it in a string and output the string to the console.  However, the actual work is done in the Getdocumentat () method. Request a document from the server The Getdocumentat () method handles how you can get a document from the Web on the actual work: public string Getdocumentat (string urlstring) {
StringBuffer document = new StringBuffer ();
try {
URL url = new URL (urlstring);
URLConnection conn = Url.openconnection ();
BufferedReader reader = new BufferedReader (New InputStreamReader (Conn.getinputstream ()));
String line = null;
while (line = Reader.readline ())!= null)
Document.append (line + "\ n");
Reader.close ();
catch (Malformedurlexception e) {
System.out.println ("Unable to connect to URL:" + urlstring);
catch (IOException e) {
System.out.println ("IOException when connecting to URL:" + urlstring);
}
return document.tostring ();
The Getdocumentat () method has a string parameter containing the URL of the document that we want. We first create a line that StringBuffer to save the document. Next, we use the parameter urlstring to create a new URL.  Then, we create a urlconnection and open it: urlconnection conn = Url.openconnection (); Once we have a urlconnection, we get its inputstream and wrap it up as a inputstreamreader, and then we wrap it into bufferedreader so that we can read the lines of the document that we get from the server, This packaging technique is often used when dealing with sockets in Java code.   Before we continue to study you must be familiar with it: BufferedReader reader =new BufferedReader (New InputStreamReader (Conn.getinputstream ())); With BufferedReader, we can easily read the contents of the document. We call the ReadLine () method on the reader in a while...loop loop: String line = null;
while (line = Reader.readline ())!= null)
Document.append (line + "\ n"); Blocking occurs when the ReadLine () method is invoked and the InputStream is passed in to a line terminator, such as a newline character. If not, it will continue to wait, and it will return NULL when the connection is closed, so, once we get a line, we append it to the stringbuffer of a called document, along with a newline character.  This preserves the format of the original document from the server.   When we read all the rows, we should close the BufferedReader:reader.close (); If the URL constructor supplied to urlstring is not valid, a Malformedur lexception exception will be thrown.  Similarly, if other errors occur, such as getting inputstream from the connection, the IOException will be thrown. Summary of the 1. Instantiate URL 2 with a valid URL string for the resource you want to connect to. Connect to the specified URL 3. The wrapper InputStream is connected to the BufferedReader so that you can read line 4. Read the document content with your BufferedReader 5. Close BufferedReader

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.