Java Socket Programming (II)

Source: Internet
Author: User
Tags html page interface connect readline requires socket client port number
Programming Java connection-oriented class





sockets has two main modes of operation: connection-oriented and connectionless. Connection-oriented sockets operations are like a phone call, They have to establish a connection and a call to one person. All things arrive in the same order as they set out. A connectionless sockets operation is like a mail delivery, and there is no guarantee that multiple messages may arrive in the same order as they were when they started.





which model to use is the need for postal applications. If reliability is more important, it's better to use a connection-oriented operation. For example, file servers require the correctness and order of their data. If some data is lost, the effectiveness of the system will be lost. Some servers, For example, send some chunks of data intermittently. If the data is lost, the server does not want to send it again. Because when the data arrives, it may be obsolete. Ensuring that the data is ordered and correct requires additional operational memory consumption, and additional costs will reduce the system's response rate.





operation using datagram protocol. A datagram is a stand-alone unit that contains all of the information about this delivery. Think of it as an envelope, it has the destination address and the content to send. The socket in this mode does not need to connect a socket for a purpose, It simply throws out the datagram. Connectionless operations are fast and efficient, but data security is poor.





connection-oriented operations use the TCP protocol. A socket in this mode must obtain a connection to the socket of the destination before sending the data. Once the connection is established, sockets can use a stream interface: Open-read-write-close. All messages sent are received in the same order at the other end. Connection-oriented operations are less efficient than connectionless operations, but the data is more secure.





Sun has always been a supporter of network building, so it is not surprising to support sockets in Java. In fact, Java reduces the difficulty of building a sockets program. Each transport mode is encapsulated into a different class. The class for the connection will be discussed first.








there are two forms of connection-oriented classes in Java, which are the client and server side. This is the simplest part of the client, so let's talk about it first.





Listing 9.1 lists a simple client-side program. It sends a request to a server, retrieves an HTML document, and displays it on the console.





9.1 A simple socket client





import java.io.*;


import java.net.*;


/**


* A simple program to retrieve an HTML page from the server


* Note: Merlin is the name of the local machine


*/


public class Simplewebclient {


public static void Main (String args[])


{


Try


{


//Open a client socket connection


Socket CLIENTSOCKET1 = new socket ("Merlin", 80);


System.out.println ("Client1:" + clientSocket1);


//Get a webpage


GetPage (CLIENTSOCKET1);


}


catch (unknownhostexception Uhe)


{


System.out.println ("unknownhostexception:" + Uhe);


}


catch (IOException IoE)


{


System.err.println ("IOException:" + IoE);


}


}


/**


* Requests a page through the established connection, displays the response and then closes the socket


*/


public static void GetPage (Socket clientsocket)


{


Try


{


//requires input and output streams


DataOutputStream outbound = new DataOutputStream (


Clientsocket.getoutputstream ());


DataInputStream inbound = new DataInputStream (


Clientsocket.getinputstream ());


//Send HTTP requests to the server


outbound.writebytes ("get/http/1.0\r\n\r\n");


/read out response


String Responseline;


while ((Responseline = Inbound.readline ())!= null)


{


//Show each line


System.out.println (Responseline);


if (Responseline.indexof ("")!=-1)


break;


}


//Clear


Outbound.close ();


Inbound.close ();


Clientsocket.close ();


}


catch (IOException IoE)


{


System.out.println ("IOException:" + IoE);


}


}


}








recalls that a client sends a connection to a listening server socket. The sockets of the client is established with the socket class. The following program establishes a client socket and connects to a host:





Socket clientsocket = new socket ("Merlin", 80);





The first parameter is the name of the host you want to connect to, and the second parameter is the port number. A host name specifies the name of the destination. The port number specifies which application to receive. In our case, must specify 80, Because it is the port of the default HTTP protocol. Additional well-known ports are listed in Table 9.1, see:





well-known end products:





Echo 7





Daytime 13





Daytime 13





FTP 21





Telnet 23





SMTP 25





Finger 79





HTTP 80





POP3 110





because the socket class is connection-oriented, it provides a stream interface that can be read and written. A class in the Java.io package can be used to access a connected socket:





DataOutputStream outbound = new DataOutputStream (


Clientsocket.getoutputstream ());


DataInputStream inbound = new DataInputStream (Clientsocket.getinputstream ()


);





once the flow is established, the general flow operation can be done:





outbound.writebytes ("get/http/1.0\r\n\r\n");


String Responseline;


while ((Responseline = Inbound.readline ())!= null)


{


System.out.println (Responseline);


}





above the applet requests a Web page and displays it. When the program completes, the connection must be closed.





Outbound.close ();


Inbound.close ();


Clientsocket.close ();





note the socket stream must be closed first. All of the socket streams must be closed before the socket closes. This applet is very simple, but all client programs must follow the basic steps below:





1. Establish a client socket connection.





2. Gets the read and write stream of the socket.





3. Using Flow.





4. Close the stream.





5. Close the socket.





using a server-side socket is just a bit more complicated, and it's going to be mentioned below.





 





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.