Java beginners practice tutorial-network programs

Source: Internet
Author: User

Java is doing well in network programming. The main purpose of java is to create a network. It can easily access resources on the network. This section describes two network communication mechanisms: URL communication and Socket communication.
URL indicates the reference or address of a resource on the Internet. Java network applications also use URLs to locate Internet resources to access. In jdk, java.net. URL is also a class that encapsulates URL details. At present, you can understand the URL as the URL. default. aspx is a URL. http is the protocol name (Hypertext Transfer Protocol) separated by ": //" www.tbwshc.com is the host name. Default. aspx is the file name. The port number is not written. The default value is 80.

Practice:

 

Import java.net .*;

Public class ParseURL {

Public static void main (String [] args) throws MalformedURLException {

URL url = new URL ("http://www.100jq.com: 45175/default. aspx ");

System. out. println ("protocol is" + url. getProtocol ());

System. out. println ("host is" + url. getHost ());

System. out. println ("file name is" + url. getFile ());

System. out. println ("port number is" + url. getPort ());

}}

/*

The URL object provides many methods such

GetProtocol ()

GetHost ()

GetFile ()

GetPort ()

*/

 

You can use a URL to read files or resources, or use URLConnection to read tb data, or write data to cgi scripts.

Practice:

 

Import java.net .*;

Import java. io .*;

Public class URLConnectionReader {

Public static void main (String [] args) throws IOException {

URL google = new URL ("");

URLConnection g = google. openConnection ();

BufferedReader in = new BufferedReader (new InputStreamReader (g. getInputStream ()));

String inputLine;

While (inputLine = in. readLine ())! = Null)

System. out. println (inputLine );

In. close ();

}}

 

The URL and URLConnection classes provide high-level network access. Sometimes access at a lower level is required. When writing a C/S model program, you need to use the Socket communication mechanism. Because you do not have to access files on the network.

Practice:

 

// Write a client application first
Import java.net .*;

Import java. io .*;

Public class SimpleClient {

Public static void main (String args []) {

Try {

// Open the server connection at Port 5432

// Use localhost and 127.0.0.1 here

Socket s1 = new Socket ("127.0.0.1", 5432 );

// Connect a reader to this port. Note that the port cannot occupy other

BufferedReader br = new BufferedReader (

New InputStreamReader (s1.getInputStream ()));

// Read the input data and print it on the screen

System. out. println (br. readLine ());

// Close the stream and connection upon completion

Br. close ();

S1.close ();

} Catch (ConnectException connExc ){

System. err. println ("cocould not connect to the server .");

} Catch (IOException e ){

// Ignore

}}}

// This is a server application

Import java.net .*;

Import java. io .*;

Public class SimpleServer {

Public static void main (String args []) {

ServerSocket s = null;

// Register the service port 5432

Try {

S = new ServerSocket (5432 );

} Catch (IOException e ){

E. printStackTrace ();

}

// Run and receive the listener, and keep repeating forever. Because the server is always enabled

While (true ){

Try {

// Wait for a connection request

Socket s1 = s. accept ();

// Get the output stream of the port

OutputStream s1out = s1.getOutputStream ();

BufferedWriter bw = new BufferedWriter (

New OutputStreamWriter (s1out ));

// Send a string

Bw. write ("Welcome to baibaiquan software project research office! \ N ");

// Close the connection, but it is not the socket of the server.

Bw. close ();

S1.close ();

} Catch (IOException e ){

E. printStackTrace ();

}}}}

 

Download href = "http://java.chinaitlab.com/download/07072213182935.rar" target = _ blank> package the above example

The execution of this program is not the same as that of others. After compiling the two files with javac. Then, press start to open another window. The window opened with the start command inherits the features of the original window. 26-1

 

Figure 26-1

Then execute the server program java SimpleServer in the original window. execute java SimpleClient in the new window and you will see the result. NOTE: If bindException is thrown when the server is started, the port 5432 is occupied by other programs and can be changed to another port number. Generally, when using a port, it is recommended that the number be less than. Many ports with a 1024th speed are dedicated ports.
Author: tbwshc

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.