Home | | Web Programming | TCP/IP Client Sockets - Java

Chapter: Java The Complete Reference : The Java Library : Networking

TCP/IP Client Sockets - Java

TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point, stream-based connections between hosts on the Internet.

TCP/IP Client Sockets

 

TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point, stream-based connections between hosts on the Internet. A socket can be used to connect Java’s I/O system to other programs that may reside either on the local machine or on any other machine on the Internet.

 

There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients. The ServerSocket class is designed to be a "listener," which waits for clients to connect before doing anything. Thus, ServerSocket is for servers. The Socket class is for clients. It is designed to connect to server sockets and initiate protocol exchanges. Because client sockets are the most commonly used by Java applications, they are examined here.

 

The creation of a Socket object implicitly establishes a connection between the client and server. There are no methods or constructors that explicitly expose the details of establishing that connection. Here are two constructors used to create client sockets:


Socket defines several instance methods. For example, a Socket can be examined at any time for the address and port information associated with it, by use of the following methods:


InetAddress getInetAddress( ) : Returns the InetAddress associated with the Socket object. It returns null if the socket is not connected.

 

int getPort( ) : Returns the remote port to which the invoking Socket object is connected. It returns 0 if the socket is not connected.

 

int getLocalPort( ) : Returns the local port to which the invoking Socket object is bound. It returns –1 if the socket is not bound.


You can gain access to the input and output streams associated with a Socket by use of the getInputStream( ) and getOuptutStream( ) methods, as shown here. Each can throw an IOException if the socket has been invalidated by a loss of connection. These streams are used exactly like the I/O streams described in Chapter 20 to send and receive data.


InputStream getInputStream( ) throws IOException : Returns the InputStream associated with the invoking socket.

 

OutputStream getOutputStream( )throws IOException : Returns the OutputStream associated with the invoking socket.


Several other methods are available, including connect( ), which allows you to specify a new connection; isConnected( ), which returns true if the socket is connected to a server; isBound( ), which returns true if the socket is bound to an address; and isClosed( ), which returns true if the socket is closed. To close a socket, call close( ). Closing a socket also closes the I/O streams associated with the socket. Beginning with JDK 7, Socket also implements AutoCloseable, which means that you can use a try-with-resources block

 

to manage a socket.

 

The following program provides a simple Socket example. It opens a connection to a "whois" port (port 43) on the InterNIC server, sends the command-line argument down the socket, and then prints the data that is returned. InterNIC will try to look up the argument as a registered Internet domain name, and then send back the IP address and contact information for that site.

// Demonstrate Sockets.

import java.net.*; import java.io.*;

 

class Whois {

 

public static void main(String args[]) throws Exception { int c;

 

    Create a socket connected to internic.net, port 43. Socket s = new Socket("whois.internic.net", 43);

 

    Obtain input and output streams.

 

InputStream in = s.getInputStream();

 

OutputStream out = s.getOutputStream();

 

// Construct a request string.

 

String str = (args.length == 0 ? "MHProfessional.com" : args[0]) + "\n";

// Convert to bytes.

 

byte buf[] = str.getBytes();

 

    Send request. out.write(buf);

 

    //Read and display response.

 

    while ((c = in.read()) != -1) { System.out.print((char) c);

 

}

 

s.close();

 

}

 

}

 

If, for example, you obtained information about MHProfessional.com, you’d get something similar to the following:

 

Whois Server Version 2.0

 

Domain names in the .com and .net domains can now be registered

 

with many different competing registrars. Go to http://www.internic.net for detailed information.

 

Domain Name: MHPROFESSIONAL.COM Registrar: CSC CORPORATE DOMAINS, INC. Whois Server: whois.corporatedomains.com Referral URL: http://www.cscglobal.com Name Server: NS1.MHEDU.COM

Name Server: NS2.MHEDU.COM

 

.

 

.

Here is how the program works. First, a Socket is constructed that specifies the host name "whois.internic.net" and the port number 43. Internic.net is the InterNIC web site that handles whois requests. Port 43 is the whois port. Next, both input and output streams are opened on the socket. Then, a string is constructed that contains the name of the web site you want to obtain information about. In this case, if no web site is specified on the command line, then "MHProfessional.com" is used. The string is converted into a byte array and then sent out of the socket. The response is read by inputting from the socket, and the results are displayed. Finally, the socket is closed, which also closes the I/O streams.

In the preceding example, the socket was closed manually by calling close( ). If you are using JDK 7 or later, then you can use a try-with-resources block to automatically close the socket. For example, here is another way to write the main( ) method of the previous program:

 

 

// Use try-with-resources to close a socket.

 

public static void main(String args[]) throws Exception { int c;

 

    //Create a socket connected to internic.net, port 43. Manage this

 

    //socket with a try-with-resources block.

 

try ( Socket s = new Socket("whois.internic.net", 43) ) {

 

    //Obtain input and output streams.

    InputStream in = s.getInputStream();

    OutputStream out = s.getOutputStream();

 

    Construct a request string.

 

String str = (args.length == 0 ? "MHProfessional.com" : args[0]) + "\n"; // Convert to bytes.

 

byte buf[] = str.getBytes();

 

    Send request. out.write(buf);

 

    //Read and display response.

 

    while ((c = in.read()) != -1) { System.out.print((char) c);

 

}

 

}

 

// The socket is now closed.

 

}

 

In this version, the socket is automatically closed when the try block ends.

 

So the examples will work with earlier versions of Java and to clearly illustrate when a network resource can be closed, subsequent examples will continue to call close( ) explicitly. However, in your own code, you should consider using automatic resource management since it offers a more streamlined approach. One other point: In this version, exceptions are still thrown out of main( ), but they could be handled by adding catch clauses to the end of the try-with-resources block.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Java The Complete Reference : The Java Library : Networking : TCP/IP Client Sockets - Java |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.