A secret class in Java Socket programming

Source: Internet
Author: User
A secret class in Java socket programming

Introduction

The Java platform implements socket in the java.net package. In this article, we will use the following three classes in the java.net package to work:

· Urlconnection

· Socket

· Serversocket

There are more classes in the java.net package, but these are the most common ones. Let's start with urlconnection, this class provides the method of using socket in your Java code without understanding the underlying mechanism of socket.

You can use sockets without even trying.

To connect to a URL, follow these steps:

· Create a urlconnection

· Use different setter methods to configure it

· Connect to urlconnection

· Interact with different getter Methods

Next, we will use some examples to demonstrate how to use urlconnection to request a document from a server.

Urlclient class

We will 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 first import the java.net and java. io packages.

An instance variable for our class is used to save a URLConnection

Our class contains a main () method used to process logic flows that browse a document. Our class also contains the getDocumentAt () method used to connect to the server and request documents, below we will explore the details of these methods.

Browse documents

The main () method is used to process the logic flow for browsing 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 only creates a new URLClient class instance and uses a valid URL String to call the getDocumentAt () method. When a document is returned, we store it in a String and output the String to the console. However, the actual work is completed in the getDocumentAt () method.

Request a document from the server

How to obtain a document from the web in actual work using the getDocumentAt () method:

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 type parameter that contains the URL of the document we want to get. First, create a StringBuffer to save the line of the document. Next, we use the passed parameter urlString to create a new URL. Then, we create a URLConnection and open it:

URLConnection conn = url. openConnection ();

Once a URLConnection exists, we obtain its InputStream and package it into InputStreamReader. Then we encapsulate it into a BufferedReader so that we can read the lines of documents obtained from the server, this packaging technology is often used when processing socket in java code. You must be familiar with it before we continue learning:

BufferedReader reader = new BufferedReader (new InputStreamReader (conn. getInputStream ()));

With BufferedReader, we can easily read the document content. We call the readline () method on reader in a while... loop:

String line = null;
While (line = reader. readLine ())! = Null)
Document. append (line + "/n ");

When the readLine () method is called and the line terminator (for example, line feed) is passed in from InputStream, blocking occurs. If not, it will continue to wait. When the connection is closed, it will return null. In this case, once we get a row, we append it to the StringBuffer of a call document together with a linefeed. In this way, the format of the original document on the slave server is retained.

After reading all rows, we should disable BufferedReader:

Reader. close ();

If the URL constructor provided to urlString is invalid, A MalformedUR tralexception exception is thrown. If other errors occur, for example, when InputStream is obtained from a connection, an IOException is thrown.

Summary

1. instantiate a url with a valid URL String of the resource you want to connect

2. Connect to the specified URL

3. Wrap InputStream to connect to BufferedReader so that you can read rows

4. Use your BufferedReader to read the document content

5. Disable 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.