Scrigroup - Documente si articole

     

HomeDocumenteUploadResurseAlte limbi doc
AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Network And Sockets

java



+ Font mai mare | - Font mai mic



Network And Sockets

A computer network is a communication system for connecting two or more hosts. Hosts can be anything from microcomputers to super-computers, which makes establishing communication among them an involved task for programmers. The goal of Java's internetworking facilities is to hide the details of different physical networks from programmers. This allows the programmer to worry about the more romantic pursuits of network programming and not to be bogged down by the trivial details of many different systems. However, this grand achievement of hiding details was no walk in the park for the Java designers. Hosts can have vastly different physical attributes and may be dedicated to widely varying tasks. What is needed to make all these different species of systems happy and able to communicate with each other is a common protocol. A protocol is a set of rules and conventions between the communicating participants. Using the higher-level protocol abstractions, the programmer can create Java programs quickly and with increased productivity. They need not build special versions of application software to move and translate data between different types of machines.



This chapter introduces the basic concepts of networking. It discusses client-server applications, tells you how to identify a host using an Internet address, and explains what sockets are. Following a summary of the classes and interfaces covered in this chapter are detailed explanations of the methods presented with examples to help you build networking applications in Java. The project you will develop in this chapter is a client-server application. The client sends messages to the server requesting it to send the contents of a file. The server processes the request and sends the contents of the file line-by-line. On receiving the file's contents from the server, the client displays it on a window.

Client-Server Applications

There are several models for building network applications. The most widely used model is the client-server model which involves two types of processes: a server process and a client process. When you start a server process on a host, it waits for a client to contact it. A client process, started on the same host or a different one, sends a request to the server over the network. The server responds to the request by sending a reply. Figure 10-1 illustrates a typical exchange in a client-server application.


Figure 10-1  A client-server communication scenario(a) Host A, as a client sends a request for service to server located on host B(b) After processing the request, the server sends a reply to the client

The communication between a server and a client can be accomplished in two ways: connection-oriented or connectionless. In a connection-oriented transfer, a dedicated connection is established between a server and a client. They use this connection to exchange information. Given that the other type is called connectionless, it doesn't seem like a lot of communication actually happens between them. Then how do they communicate? The client sends the request by specifying the server's address. This is received by the server, who is waiting for a message from some client. The server obtains the client address from the message to which it may then respond.

Connection-Oriented Protocol

In a connection-oriented communication, the client and the server have a dedicated link established between them. It is similar to the telephone communication system. When you call someone and the called phone number exists, there is a dedicated line for you to converse. Whatever you speak is guaranteed to be heard on the other side, with probably an element of delay. Also the words you speak are heard in the exact order in which they were spoken. The connection-oriented protocol is a reliable protocol. The messages sent between any two processes are guaranteed to be delivered and in the proper sequence. Most of the networking applications are connection oriented, as they require reliable communication protocol. TCP (Transfer Control Protocol) is a connection-oriented protocol in the TCP/IP family.

Connectionless Protocol

In a connectionless protocol, there is no dedicated link between the client and the server. They send messages as datagram packets, each of which contains the destination address. The underlying network will decipher the targeted destination address from a packet and routes the packet to the destination. In this sense, each packet is self-contained. They have the information about the sender and the intended receiver, apart from the core message. You can consider such a communication to be similar to the U.S. Postal service. Each letter you send has its destination address contained in it and the postal department takes the necessary steps to route the mail to the destination. But you should note that the postal department guarantees neither the delivery nor the sequence of delivery. Similarly, in the connectionless protocol, the packets are not guaranteed to be delivered, and even it they are delivered, the order of delivery is not guaranteed. Then the obvious question is: Where will you ever use the connectionless protocol for communication? You can use this protocol where the order of messages is not critical. For example, consider a time server application. The server can keep sending the updated time to the client. The client need not assume any order of delivery. As it receives messages, logic can be built in the client application to sense the sequence of received messages. In this application, missing packets will not create any havoc. In the TCP/IP family, the UDP is the connectionless protocol.

Internet Address

To identify a particular host in the Internet you need an Internet address. Using Internet addressing, a host can communicate with another host located in the same physical network or subnet, or in a different physical network, where both networks are linked by the Internet. Hence, hosts separated geographically can communicate effectively by addressing each other by their Internet address. Figure 10-2 illustrates the distribution of hosts among the Internet, divided into different physical networks.


Figure 10-2  Distribution of hosts among different subnets over the Internet

An Internet address is usually written as four decimal numbers, which are separated by decimal points. Each decimal digit in this address encodes one byte of the 32-bit Internet address. The Internet address maps to a unique host and the host can be addressed by a unique combination of the hostname and the name of the particular network the host is a part of (i.e., domain name). Conceptual representation of Internet addresses is represented in Figure 10-3.


Figure 10-3  Conceptual representation of Internet addressing

In the Internet address representation, Internet Id identifies a network in the Internet. Subnet Id represents a local area network(subnet) and Host Id is the identifier for a given host in the subnet. The combination of these three identifiers represents a unique host in the Internet. Here 128.230.32.66 is the Internet address that maps to ratnam.cat.syr.edu, where ratnam is the machine name and is a part of cat.syr.edu network domain. In this example, host Id is 66, subnet Id is 32 and the Internet Id is 128.230. The InetAddress Class in Java encapsulates the methods required to manipulate with an Internet address in a networking application.

Why Sockets?

To provide an interface between your application and the network you need a socket. Most of the communication in a client-server application is point-to-point, where the endpoint of such communication is an application (client or server). A socket acts as an endpoint for communication between processes on a single system or on different systems. The applications communicate between themselves by sending messages to one another. These messages are sent as a sequence of packets at the network level. For each packet that is sent, there has to be a receiving end. Sockets form such an end point to receive packets, as well as to send messages. Application programs request the operating system to create a socket when in need. The system returns a socket identifier, in the form of a small integer that the application program uses to reference the newly created socket. A networking application can be identified by a <host, socket> pair (the host on which it is running and the socket at which it is listening for messages).

Java provides separate classes which encapsulate the functionality of client and server sockets. The Socket class is used to represent sockets on the client side, while the server side sockets are represented by the ServerSocket class. The Socket and ServerSocket form the client and server side sockets in a connection oriented protocol. Once a link is established between the client and the server, they can exchange messages until one of them closes the connection. Whereas, the sockets, in the case of connectionless protocol, are represented by the DatagramSocket class. In this case, both the client and the server are associated to a datagram socket. Every time a message is to be sent, they create a DatagramPacket containing the destination address and port number along with the message to be sent. This packet gets delivered (if it does get delivered) to the targeted application. To implement various such policies for communication between a client and a server, Java provides a SocketImpl Class. SocketImplFactory is an Interface that can be used to generate more instances of the SocketImpl Class for use in your applications.

Network and Socket Summaries

Table 10-1 summarizes the classes and interfaces necessary for developing network applications using Java.

Table 10-1 Class and interface description


Class/Interface

Description


InetAddress

Represents Internet addresses.

ServerSocket

This class represents the server socket. It uses a SocketImpl class to implement the actual policies regarding socket operations.

Socket

This class represents the client socket. It uses a SocketImpl class to implement the actual socket policies for its operations.

DatagramSocket

This class represents a datagram socket, which is an implementation of the connectionless protocol.

DatagramPacket

This class represents a datagram packet, which is self-contained, with the details of the destination host and the data to be sent.

SocketImpl

This should be subclassed to provide actual implementation. This class implements the actual socket policies for ServerSocket and Socket classes.

SocketImplFactory

A factory for creating actual instances of SocketImpl is defined in this interface.

InetAddress

Purpose

Use InetAddress to represent Internet addresses.

Syntax

public final class InetAddress extends Object

Description

The InetAddress class represents the Internet Address. The methods of InetAddress provide functionality to gain information about raw IP address, hostname, and network address of a host machine, and hash code of the Internet address in the hashtable. Figure 10-4 shows the inheritance diagram for the InetAddress class.


Figure 10-4  Class diagram for InetAddress class

PackageName

java.net

Imports

import java.net.InetAddress;

Constructors

None; see getByName(String) method

Parameters

None

Example

Use the getByName(String) method of the InetAddress class to create an instance of InetAddress. No public constructors are provided for InetAddress, so an instance of InetAddress cannot be created using the new statement. In the following example, the Client obtains the InetAddress of the server to connect to. It uses the hostname of the server to create an InetAddress object.

import java.net.InetAddress;

public class Client extends Applet implements Runnable

equals(Object)

ClassName

InetAddress

Purpose

Compares the specified object with the object on which the method is invoked.

Syntax

public boolean equals(Object objct)

Parameters

objct

The object with which the invoked object is to be compared.

Description

The method compares the Internet address of the specified object with that of the object on which the method is invoked. The objects are considered equal if their Internet addresses are the same.

Imports

import java.net.InetAddress;

Returns

The return type of the method is boolean. It returns true if the objects compared are the same; if the objects are not the same, the method returns false.

See Also

class InetAddress

Example

The following example obtains the InetAddress of both the Client and the Server. It compares these objects to verify whether the Client is running on the same host as the Server by using the equals(object) method of InetAddress class. The result is displayed.

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

public class Client extends Applet implements Runnable
public void init()
:
*/

public void compareHosts()
}

getAddress()

ClassName

InetAddress

Purpose

This method returns the raw IP address of the object in network byte order.

Syntax

public byte[] getAddress()

Parameters

None.

Description

The method returns the raw IP address representation of the Internet address in 32-bit format in network byte order. It returns the addr[] byte array, member of the InetAddress. addr[0] contains the highest order byte position. addr[] is an array of bytes so that this method is extendable for 64-bit IP addresses also.

Imports

import java.net.InetAddress;

Returns

The value of the addr[] byte array in InetAddress; the return type is a byte array.

See Also

The class InetAddress

Example

The following example gets the raw IP address of machine on which the Server is running, servHost, into a byte array.

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

public class Client extends Applet implements Runnable

getAllByName(String)

ClassName

InetAddress

Purpose

Returns an array of all InetAddresses that correspond to the specified hostname.

Syntax

public static synchronized InetAddress[] getAllByName(String host_name) throws UnknownHostException

Parameters

host_name

The hostname of the machine, the InetAddresses which you are trying to obtain.

Description

A host can have multiple InetAddresses (Internet address mapping). To access all of those InetAddresses, the hostname is passed to the getAllByName method. The method finds out the Internet addresses of the given host and returns all of them as an array of InetAddress objects.

Imports

import java.net.InetAddress;

Returns

The return type of this method is an array of InetAddresses. The array elements contain all the InetAddresses of the specified host.

See Also

The class InetAddress; method InetAddress.getByName(String hostname)

Example

In the following example, the Client obtains all the InetAddresses of the Server host into an array of InetAddress.

import java.net.InetAddress;

public class Client extends Applet implements Runnable

getByName(String)

ClassName

InetAddress

Purpose

This method gets the InetAddress of the specified host.

Syntax

public static synchronized InetAddress getByName(String host_name) throws UnknownHostException

Parameters

host_name

The hostname of the machine whose InetAddress is returned by this method.

Description

This method returns the InetAddress of a specified host. The InetAddress class does not have public constructors. You can use this method to create an instance of the InetAddress for a particular host.

Imports

import java.net.InetAddress;

Returns

The return value of the method is InetAddress. It returns the InetAddress for the specified host.

See Also

The class InetAddress; method InetAddress.getAllByName(String)

Example

Refer to the code example in the class InetAddress API where the method getByName is used to obtain the InetAddress of the server host by specifying the server's hostname.

getHostName()

ClassName

InetAddress

Purpose

This method returns the hostname for this InetAdress.

Syntax

public String getHostName()

Parameters

None

Description

The method returns the hostname of a machine with the same address as this InetAddress. So if you know the IP address of a machine, you can find out its hostname by using this method on the InetAddress object of that address.

Imports

import java.net.InetAddress;

Returns

The return type of the method is String and its value is the hostname of the machine with this IP address.

See Also

The class InetAddress

Example

The following example illustrates the usage of the getHostName() method to obtain the hostname of the Client.

import java.net.InetAddress;

public class Client extends Applet implements Runnable catch (IOException ioE);

}

getLocalHost()

ClassName

InetAddress

Purpose

This method gets the InetAddress of the local host.

Syntax

public static InetAddress getLocalHost() throws UnknownHostException

Parameters

None

Description

This method finds the Internet address of the local machine executing this program. It creates an instance of InetAddress with this address and returns the InetAddress object. getLocalHost() can be used to create an instance of InetAddress for the local machine.

Imports

import java.net.InetAddress;

Returns

The return type of the method is InetAddress. It returns the InetAddress object representing the Internet address of the local machine.

See Also

The class InetAddress; method InetAddress.getByName()

Example

Refer to the example in getHostName() which contains a call to this method.

hashCode()

ClassName

InetAddress

Purpose

Returns the hash code of this InetAddress object.

Syntax

public int hashCode()

Parameters

None

Description

The method returns the hash code, to be used as an index into the hashtable to access this InetAddress object. All the InetAddresses accessed during the program execution are cached in a hashtable. This is done for faster access of previously accessed Internet addresses.

Imports

import java.net.InetAddress;

Returns

The return type of this method is int, and the value is the hash code of this Internet address.

See Also

The class InetAddress

Example

The following example gets the hash code for the InetAddress object of the server host.

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

public class Client extends Applet implements Runnable

toString()

ClassName

InetAddress

Purpose

This method converts the InetAddress to a string.

Syntax

public String toString()

Parameters

None

Description

This method converts the InetAddress to a String by overriding the toString() method of the Object class. Raw IP address, host name can also be obtained by manipulating with the returned String.

Imports

import java.net.InetAddress;

Returns

The return type of the method is String. It returns the String form of the InetAddress.

See Also

The class InetAddress, method InetAddress.getHostName()

Example

Refer to the code example for getHostName() method of InetAddress class.

ServerSocket

Purpose

Use ServerSocket to implement a server.

Syntax

public final class ServerSocket extends Object

Description

The ServerSocket class represents the server in a client-server application. This class implements the actual socket policies that go along with a server. It uses a default SocketImpl class to implement its server policies. These policies can be changed by implementing a concrete subclass of the abstract SocketImpl class. This change in policies can be made effective by setting the SocketImplFactory, using the setSocketFactory method. The methods of ServerSocket class provide the functionality to create a server socket, accept connection from a client and get the specifics of the particular ServerSocket object (namely the port to which the server is connected), and the string form of implementation address, file descriptor, and port. A ServerSocket object is bound to the local machine on which it is created. A port number is specified for the ServerSocket to bind and listen for connections. Figure 10-5 shows the inheritance diagram for the class ServerSocket.


Figure 10-5  Class diagram for ServerSocket class

PackageName

java.net

Imports

import java.net.ServerSocket;

Constructors

public ServerSocket(int port) throws IOException
public ServerSocket(int port, int lisn_time) throws IOException

Parameters

port

Local port number to which the server binds.

lisn_time

The amount of time the server will listen at the port for connection.

Example

In the following example, an instance of ServerSocket is created and is bound to the port number specified by port. The listening time for a connection is set to 10. After creation, the socket waits for a connection from a client and accepts the connection. After performing its services, the server socket is closed.

import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

public class Server catch (IOException io)
try catch (IOException io)

// get the string form of the server socket
String str = serv.toString();
System.out.println('String form of server socket is : ' + str);

/* perform the services */

/* Close the socket connection now */
try catch (IOException io)
} /* end of main() */
} /* end of class Serv */

accept()

ClassName

ServerSocket

Purpose

Blocks until a connection is made with a client. It returns a client socket after the connection is established. This socket is used for further communication with the client.

Syntax

public Socket accept() throws IOException

Parameters

None.

Description

This method blocks for a client connection by listening to the port it has bound to. When a client attempts to connect to this server socket, this method accepts the connection and returns a client socket (instance of the Socket class). Optionally, the time limit for listening can also be specified. If it is specified during construction, then the server blocks for connection for only the specified time. This socket is later used for all the communication between the server and its client. The output stream of this socket is the input for the connected client and vice versa. An IOException is thrown if any error has occurred while establishing the connection. This has to be caught and relevant exception handling steps should be taken.

Imports

import java.net.ServerSocket;
import java.net.Socket;

Returns

The return type of the method is a Socket. It returns the Socket instance created on the server's side to communicate with the connected client.

See Also

The class ServerSocket; class Socket

Example

Refer to the example for class ServerSocket, given above. In that example, an instance server of ServerSocket is created and, after creation, the socket waits for a connection from a client and accepts the connection using the accept() method.

close()

ClassName

ServerSocket

Purpose

Closes the socket of the server.

Syntax

public void close() throws IOException

Parameters

None.

Description

The method closes the socket to which the server is bound. This implies that any other client socket connected to this server should have been closed prior to this method call, for proper behavior. So before calling the close method on a server, all the clients connected to it should have closed their socket connections.

Imports

import java.net.ServerSocket;

Returns

None.

See Also

The class ServerSocket; Exception IOException

Example

Refer the example for the API class ServerSocket

getInetAddress()

ClassName

ServerSocket

Purpose

Returns the InetAddress object, representing the Internet address of the host to which the server socket is bound.

Syntax

public InetAddress getInetAddress()

Parameters

None.

Description

This method returns the InetAddress of the host machine on which the ServerSocket is bound. As a server is bound only to a local machine (optionally specifying a port number), this method helps you identify the host to which the server is created and uses this InetAddress object to access more information about the server host.

Imports

import java.net.ServerSocket;
import java.net.InetAddress;

Returns

The return type of the method is InetAddress. It returns the InetAddress object which represents the Internet Address of the host machine on which the server socket is created and bound.

See Also

The class ServerSocket; class InetAddress

Example

In the following example, an instance of ServerSocket is created. InetAddress of the server host is obtained and hostname, IP address details of that host are retrieved and printed.

import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.*;

public class Server catch (IOException io)
/* get the InetAddress of the server host */
InetAddress inet = serv.getInetAddress();

/* Get details of the server host */

String addr_str = inet.toString();
byte[] raw_ip = inet.getAddress();
System.out.println('The InetAddress of server host is : '
+ addr_str);

/* get the port number of the server socket */
int port_num = serv.getLocalPort();

if (port_num == 3001)
System.out.println('Server port# is 3001 as expected ');
else
System.out.println('Server port# is not 3001! ;-( ');

/* close the socket */
try catch (IOException io)
} /* end of main() */
} /* end of class Serv */

getLocalPort()

ClassName

ServerSocket

Purpose

Returns the port number to which the server socket connection is established and is listening.

Syntax

public int getLocalPort()

Parameters

None.

Description

This method obtains the port number to which the ServerSocket is bound and listens for connection. This number is the port number of the socket at the machine on which the ServerSocket is connected.

Imports

import java.net.ServerSocket;

Returns

The return type of the method is int. It returns the port number of the ServerSocket instance created at the server's side.

See Also

The class ServerSocket

Example

Refer to the example in the getInetAddress() method of ServerSocket class.

setSocketFactory(SocketImplFactory)

ClassName

ServerSocket

Purpose

Sets the system's server SocketImplFactory interface, which generates SockImpl instances.

Syntax

public static synchronized void

setSocketFactory(SocketImplFactory fac) throws IOException

Parameters

None.

Description

The desired policies that go with the ServerSocket class are implemented by a concrete subclass of SocketImpl. Instances of this subclass will be created by the createSocketImpl() method of the SocketImplFactory interface. When fac, an instance of this interface, is passed to this setSocketFactory() method, the member factory of ServerSocket class gets assigned. Thereafter, any instance of ServerSocket created will have the desired socket policies implemented. The SocketImplFactory can be specified only once for this ServerSocket class. This method will not normally be used by programmers, as the APIs for ServerSocket have a default SocketImpl defined and, hence, there is no need for a factory.

Imports

import java.net.ServerSocket;

Returns

None.

See Also

The class ServerSocket; class SocketImpl; interface SocketImplFactory

Example

The following code outline illustrates how to subclass SocketImpl and use it to generate instances of that class using a factory. This factory, MyFac, is set to be the member factory of server class Server so that any new instances of Server will implement the desired policies as in MySockImpl.

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

class MySockImpl extends SocketImpl

/** MyFac is the concrete class implementing SocketImplFactory for
this application */

class MyFac implements SocketImplFactory


/** Assign MyFac as the factory member of class Serv, representing a
server socket */

public class Server /* end of main() */
} /* end of class Serv */

toString()

ClassName

ServerSocket

Purpose

To obtain the implementation address, file descriptor, and port number to which this ServerSocket is connected.

Syntax

public String toString()

Parameters

None.

Description

This method creates a String object containing the port number, file descriptor, and address to which the ServerSocket is bound to. The details are merged into string form within a String object. This method overrides the toString() method in the class Object.

Imports

import java.net.ServerSocket;

Returns

The return type of the method is String. The returned String object contains the port number, file descriptor, and address of the machine on which the SeverSocket is bound.

See Also

The class ServerSocket; class Object (java.lang.Object)

Example

Refer to the example in ServerSocket class description.

Socket

Purpose

Use Socket to implement a client to communicate with a server.

Syntax

public final class Socket extends Object

Description

The Socket class represents a client in a client-server application. This class implements the actual socket policies that go along with a client. It uses a default SocketImpl class to implement its client socket policies. These policies can be changed by implementing a concrete subclass of the abstract SocketImpl class. This change in policies can be made effective by setting the SocketImplFactory, using the setSocketImplFactory method. The methods of the Socket class provide the functionality to create a client socket, by connecting to a server, and to obtain necessary input and output streams for communication. The class contains methods to find out the specifics of the particular Socket object namely, the port to which the client is connected, the string form of implementation address, and the port number. Figure 10-6 shows the inheritance diagram of the Socket class.


Figure 10-6  Class diagram for Socket class

PackageName

java.net

Imports

import java.net.Socket;

Constructors

public Socket(String host, int port) throws IOException
public Socket(String host, int port, boolean sock_type) throws IOException
public Socket(InetAddress inet, int port) throws IOException
public Socket(InetAddress inet, int port, boolean sock_type) throws IOException

Parameters

host

Name of the host machine to connect to.

port

Local port number to which the server binds.

sock_type

Value specifying whether it is a datagram socket or a stream socket.

inet

InetAddress of the host machine to connect to.

Example

In the following example, an instance of Socket is created in the class Client. A server is initially created in the Server class. The client is connected to the server in its init() method. If the server does not exist when the client attempts a connection, an exception is thrown to indicate unavailable server connection. So the server should be started before any client attempts to request service.

import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

/* Server class */

public class Server catch (IOException io)
try catch (IOException io)
/* perform the services */

try catch (IOException io)



/* Client class implementation */

public class Client extends Applet implements Runnable catch (IOException io)
} // end of init()
/* request services from the server */

public void run()

// Applet stop
public void stop() catch (IOException ioE)
}
} // end of class Client

close()

ClassName

Socket

Purpose

Closes the socket of the client.

Syntax

public void close() throws IOException

Parameters

None.

Description

The method closes the client's socket connection to the server.

Imports

import java.net.Socket;

Returns

It does not return anything. It throws an IOException on an occurrence of an error, which has to be caught.

See Also

The class Socket; Exception IOException

Example

Refer to the example in Socket class which includes the usage of close() method.

getInetAddress()

ClassName

Socket

Purpose

Returns the InetAddress object, representing the Internet address of the host to which the client socket is connected, i.e., the server host.

Syntax

public InetAddress getInetAddress()

Parameters

None.

Description

This method returns the InetAddress of the host machine on which the Socket is connected. As a client connects to a server that is already ready and running, this method helps you identify the host on which the server is created and use this InetAddress object to access more information about the server host.

Imports

java.net.Socket;
import java.net.InetAddress;

Returns

The return type of the method is InetAddress. It returns the InetAddress object which represents the Internet Address of the host machine to which the client has established connection.

See Also

The class Socket; class InetAddress

Example

Refer to the ServerInfo() method of Client class implemented in the Client-Server Rendezvous applet at the end of this chapter.

getInputStream()

ClassName

Socket

Purpose

Returns an InputStream for this client socket.

Syntax

public InputStream getInputStream() throws IOException

Parameters

None.

Description

This method returns an InputStream for this client socket. The client receives data from the server using this stream. It can block on this InputStream until data arrives from the server. This method is also used on the server side, when the server obtains a Socket object on accepting a connection from a client. An InputStream of client is bound to the OutputStream for the Socket on server side and vice versa.

Imports

import java.net.Socket;

Returns

The return type of the method is InputStream. It returns an InputStream for the client. This object can further be used to instantiate another kind of stream suitable for service provided by the server.

See Also

The class Socket; class InputStream

Example

Usage of getInputStream() is important for client-server applications as this is the method such applications use for establishing stream channels to pass messages. The server creates an InputStream to obtain data from the client by using the Socket object, returned by the accept() call. The client obtains an InputStream from its Socket, which is effectively bound to the server's OutputStream; likewise, the client's OutputStream is bound to the InputStream of the server. Refer to the init() method of Client class in the Client-Server Rendezvous applet at the end of this chapter.

getOutputStream()

ClassName

Socket

Purpose

Returns an OutputStream for this client socket.

Syntax

public OutputStream getOutputStream() throws IOException

Parameters

None.

Description

This method returns an OutputStream for this client socket. The client sends data to the server using this stream. This method is also used on the server side, when the server sends a message to the client. An OutputStream of client is bound to InputStream for the Socket on server side and vice versa.

Imports

import java.net.Socket;

Returns

The return type of the method is OutputStream. It returns an OutputStream for the client. This object can further be used to instantiate another kind of stream, suitable for service provided by the server.

See Also

The class Socket; class OutputStream

Example

Refer to the init() method of Client class in the Client-Server Rendezvous applet at the end of this chapter.

getLocalPort()

ClassName

Socket

Purpose

Returns the local port number to which the client socket is connected.

Syntax

public int getLocalPort()

Parameters

None.

Description

This method obtains the local port number to which the Socket is connected. This number is the port number to which the client socket is connected on the local(client) side.

Imports

import java.net.Socket;

Returns

The return type of the method is int. It returns the port number to which the Socket has connected.

See Also

The class Socket

Example

In the following example, an instance of ServerSocket is created and is bound to the port number 3001. In Class Client, a client socket is created using the Socket instance and connection is established to the server. The getLocalPort() method is used to obtain the local port number.

/* Client class implementation */

public class Client catch (IOException io)

/* Obtain the port number to which the socket is connected */
int port_num = clnt.getLocalPort();
printOut(" Local port number of client is : " + port_num);

/* Close the connection from client side */

try catch (IOException io)
} /* end of main() */
} /* end of Client class definition */

getPort()

ClassName

Socket

Purpose

Returns the port number on the server side to which the client has established connection.

Syntax

public int getPort()

Parameters

None.

Description

This method obtains the port number to which the Socket is connected. This number is the port number on which the server is listening for connections and to which this client Socket object has established connection.

Imports

import java.net.Socket;

Returns

The return type of the method is int. It returns the port number to which the Socket has established connection with the server.

See Also

The class Socket

Example

The ClientInfo() method of Client class in the Client-Server Rendezvous applet at this chapter's end illustrates the use of getPort() method.

setSocketImplFactory(SocketImplFactory)

ClassName

Socket

Purpose

Sets the system's client SocketImplFactory interface, which generates SockImpl instances.

Syntax

public static synchronized void setSocketImplFactory(SocketImplFactory fac) throws IOException

Parameters

None.

Description

The desired policies that go with the Socket class are implemented by a concrete subclass of SocketImpl. Instances of this subclass will be created by the createSocketImpl() method of the SocketImplFactory interface. When fac, which is an instance of this interface, is passed to this setSocketImplFactory() method, the member factory of ServerSocket class gets assigned. Thereafter, any instance of Socket created will have the desired socket policies implemented. This method will not be normally used by programmers, as the APIs for Socket have a default SocketImpl defined and hence, there is no need for a factory.

Imports

import java.net.Socket;

Returns

None.

See Also

The class Socket; class SocketImpl; interface SocketImplFactory

Example

In the following example, class MySockImpl is implemented by subclassing SocketImpl. Instances of this class are generated by using MyFac, an implementation of SocketImplFactory. The Client's factory member is set to an instance of this factory and, thereafter, all instances of Socket are defined by the implementation in MySockImpl.

import java.net.ServerSocket;

class MySockImpl extends SocketImpl

class MyFac implements SocketImplFactory


public class Client extends Applet implements Runnable /* end of main() */
} /* end of class Client */

toString()

ClassName

Socket

Purpose

To obtain the implementation address, file descriptor, and port number to which this Socket is connected.

Syntax

public String toString()

Parameters

None.

Description

This method obtains a String object containing the port number, local port number, and address to which the Socket is bound. The details are merged into string form within a String object. This method overrides the toString() method in the class Object.

Imports

import java.net.Socket;

Returns

The return type of the method is String. The returned String object contains the port number to which the socket is connected, local port number of the socket, and address of the machine on which the Socket is connected.

See Also

The class Socket; class Object (java.lang.Object)

Example

Please refer to the example in the Socket class description which shows the details of the Socket in string form.

DatagramSocket

Purpose

Use the DatagramSocket class when you develop applications based on connectionless protocol.

Syntax

public class DatagramSocket extends Object

Description

An instance of this class forms a socket in a client-server application which is implemented using the connectionless protocol. It uses the UDP/IP protocol over the Internet. This is the class that should be instantiated on both the server and the client side, unlike ServerSocket and Socket implementations in connection-oriented protocol. When you create a DatagramSocket object on the server side, you can use the contructor that takes the port number as an argument. This way your server listens for messages at the specified port. The client's port number need not be specified. The client sends a packet to the server by specifying the port number when creating the datagram packet. This class contains the send and receive methods for handling the packets. Other methods are provided for closing a connection, getting the local port number and for cleaning up purposes. Figure 10-7 illustrates the inheritance diagram for the DatagramSocket class.


Figure 10-7  Class diagram for DatagramSocket class

PackageName

java.net

Import

import java.net.DatagramSocket;

Constructors

public DatagramSocket() throws SocketException
public DatagramSocket(int port) throws SocketException

Parameters

port

The local port number at which the datagram socket is bound.

Example

Refer to Listing 10-1 in which a message server and a message client are defined. In the constructor of the messageServer class, a datagram socket is constructed by specifying the port number 3000. That is the port at which the server waits for messages. Any client application should send a message to that port number, which is 3000 in this case, if it wants to communicate with the server. Note that in the constructor of the messageClient class (Listing 10-2), the port is not specified.

Listing 10-1 messageServer.java: A datagram server class that sends messages to clients

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

public class messageServer catch (SocketException se)

public void run()

public void processRequests() catch (Exception e)
}

public void finalize()
}

public static void main(String args[])

Listing 10-2 messageClient.java: A datagram client class that receives messages from servers

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

public class messageClient
clientSocket.close();
clientSocket = null;
serverAddr = null;
} catch (Exception e)
}

close()

ClassName

DatagramSocket

Purpose

Closes the datagram socket connection.

Syntax

public synchronized void close()

Parameters

None

Description

This method is used when a datagram socket connection is to be closed. Usually this is done during the clean-up after a client-server communication session ends. The clients should close the connection before the server.

Imports

import java.net.DatagramSocket;

Returns

None.

Example

Refer to Listing 10-1 where the close method is invoked on the server inside the finalize method. Before the garbage collector cleans up the object, the socket connection is closed. In Listing 10-2, the client closes the socket connection after receiving ten messages from the server.

finalize()

ClassName

DatagramSocket

Purpose

This method gets invoked before the DatagramSocket object is garbage collected.

Syntax

protected synchronized void finalize()

Parameters

None

Description

This method is invoked by the garbage collector Thread before cleaning up the object. You can write your clean-up routines, such as closing socket connection, closing streams, and so on, in this method. This method overrides the finalize method of the class Object.

Imports

import java.net.DatagramSocket;

Returns

None.

Example

In Listing 10-1, the server socket is closed and assigned a null value in the finalize method.

getLocalPort()

ClassName

DatagramSocket

Purpose

Obtains the port number of the datagram socket.

Syntax

public int getLocalPort()

Parameters

None

Description

This method returns the port number at which the socket is bound. This number will form a part of any packet that is sent to another datagram socket. If a message is to be sent from a client, the local port number of the server socket has to be specified when creating the packet to be sent.

Imports

import java.net.DatagramSocket;

Returns

The port number; return type is int.

Example

In Listing 10-1, the local port of the server socket is obtained by using this method. The port number 3000, the port at which the server is waiting, is displayed on the screen.

receive(DatagramPacket)

ClassName

DatagramSocket

Purpose

This method receives the datagram packet that is sent to the target DatagramSocket object.

Syntax

public synchronized void receive(DatagramPacket packet)

Parameters

packet

The packet that is to be received by the target DatagramSocket object.

Description

This method receives the packet sent to the DatagramSocket object. When invoked, this method blocks until some input is available. The packet contains the buffer of bytes (data), packet length, the destination InetAddress, and port number. Using this method along with the send method, packets are exchanged between a client and a server. Only one Thread can be invoking a receive on a socket object as the receive method is synchronized.

Imports

import java.net.DatagramSocket;

Returns

None.

Example

In Listing 10-1, the server socket receives a datagram packet in the processRequest method. After receiving the packet, the source address and port are extracted from the packet, so that a reply packet can be constructed.

send(DatagramPacket)

ClassName

DatagramSocket

Purpose

This method sends a datagram packet to a desired datagram socket.

Syntax

public void send(DatagramPacket packet)

Parameters

packet

The datagram packet that is to be sent.

Description

This method sends the specified packet to the destination address. The destination address and port number are contained within the packet. The underlying network will take the effort to deliver the packet to the destination. The delivery is not guaranteed, making the datagram communication unreliable.

Imports

import java.net.DatagramSocket;

Returns

None.

Example

In Listing 10-1, the server constructs a message, such as "This is message#1", and constructs a packet by specifying the destination address. In the processRequests method in messageServer class, the packet is sent to a client using the send method.

DatagramPacket

Purpose

Use the DatagramPacket class to send messages when you develop applications based on connectionless protocol.

Syntax

public final class DatagramPacket extends Object

Description

An instance of this class forms a datagram packet in a client-server application, which is implemented using the connectionless protocol. It uses the UDP/IP protocol over the Internet. This is the class that should be instantiated to wrap up the data to be sent. The packet is self contained with the data and the destination address. It contains the data buffer, the packet length, and the destination InetAddress and port number. A packet is sent to a target using the send method of the DatagramSocket class. A packet is received using the receive method of the DatagramSocket class. When sending a packet, the Datagram(byte[], int, InetAddress, int) constructor is used to create the packet to be sent. It is created by specifying the destination address. When receiving a packet, the DatagramPacket object is constructed using the DatagramPacket(byte[], int) constructor. In either of the constructors, if the specified length is greater than the buffer length, an IllegalArgumentException is thrown. Figure 10-8 illustrates the inheritance diagram for the DatagramPacket class.


Figure 10-8  Class diagram for DatagramPacket class

PackageName

import java.net

Imports

import java.net.DatagramPacket;

Constructors

public DatagramPacket(byte[] buffer, int length)
public DatagramPacket(byte[] buffer, int length, InetAddress dest, int port)

Parameters

buffer

The byte array containing the data.

length

The length of the data buffer.

InetAddress

IP address of the receiving datagram (where the packet is sent).

port

The port number of the receiving datagram.

Example

Refer to the processRequests method in the messageServer class in Listing 10-1. When a packet is received from the client, the size is specified as 256 and the packet is filled by using the receive method. Then the packet is constructed by specifying the destination address along with the data and sent to the client.

getAddress()

ClassName

DatagramPacket

Purpose

Obtains the InetAddress from which the datagram packet was sent.

Syntax

public InetAddress getAddress()

Parameters

None.

Description

This method returns the InetAddress from which the packet was sent. This address is a part of the packet received. Typically on the server side, the IP address of the client which sent the packet is determined using this method.

Imports

import java.net.DatagramPacket;

Returns

The Internet address of the source; return type is InetAddress.

See Also

The class InetAddress in the java.net package

Example

In Listing 10-1, the InetAddress of the client datagram is obtained by using this method. This address is in turn used to construct the reply datagram packet to specify the destination.

getData()

ClassName

DatagramPacket

Purpose

Obtains the data part of the received message.

Syntax

public byte[] getData()

Parameters

None.

Description

This method returns the data part of the datagram packet. It returns an array of bytes. If the message is expected to be a string, a String object is created by passing the byte array as a parameter for its constructor.

Imports

import java.net.DatagramPacket;

Returns

The data part of the packet; return type is byte[].

Example

In Listing 10-2, the message, received from the server, is retrieved from the packet using this method. A String object msg is constructed by passing, as a parameter, the byte array returned by this method. The message part of the received packet is printed to the screen.

getLength()

ClassName

DatagramPacket

Purpose

Obtains the length of the packet.

Syntax

public int getLength()

Parameters

None.

Description

This method returns the length of the datagram packet. It is actually the size of the buffer containing the data.

Imports

import java.net.DatagramPacket;

Returns

The packet length; return type is int.

Example

In Listing 10-2, the length of the received packet is obtained from the packet using this method.

getPort()

ClassName

DatagramPacket

Purpose

Obtains the port number from which the datagram packet was sent.

Syntax

public int getPort()

Parameters

None.

Description

This method returns the port number from which the packet was sent. This port number is a part of the packet received. Typically, on the server side, the port number of the client which sent the packet is determined using this method

Imports

import java.net.DatagramPacket;

Returns

The port number of the source; return type is int.

Example

In Listing 10-1, the port number of the client datagram is obtained by using this method. This number is, in turn, used to construct the reply datagram packet to specify the destination.

SocketImpl

Purpose

An abstract socket implementation class that should be subclassed to provide actual implementation.

Syntax

public class SocketImpl extends Object

Description

By subclassing this class and implementing the methods, desired policies for socket implementation can be provided. Then, by using the factory to generate instances of this implementation class, server socket and client socket can be implemented. This class and its methods will not be normally used by programmers because the APIs for Socket and ServerSocket have a default SocketImpl defined. Once a subclass of this class is defined, it should be generated by an implementation of SocketImplFactory interface. The factory of Socket and/or ServerSocket can be set to this factory interface, by using the setFactory method in those classes. Figure 10-9 illustrates the inheritance diagram for the SocketImpl class.


Figure 10-9  Class diagram for SocketImpl class

PackageName

java.net

Import

import java.net.SocketImpl;

Constructors

public SocketImpl()

Parameters

None.

Example

Refer to the code example in setSocketImplFactory(SocketImplFactory) method in the class Socket.

accept(SocketImpl)

ClassName

SocketImpl

Purpose

Make this server socket accept connection from a client socket with the specified SockImpl policies.

Syntax

protected abstract void accept(SocketImpl s_imp) throws IOException

Parameters

s_imp

SocketImpl of a client socket trying to connect to this server.

Description

This method should be defined in the subclass of the SocketImpl class. It makes sure that the server socket will accept connection only from a client socket with specified characteristics. This will help to build firewalls and restrict access by defining the client sockets that can connect to a server socket.

Imports

import java.net.SocketImpl;

Returns

None.

See Also

The class ServerSocket; interface SocketImplFactory

Example

The following example illustrates a sample implementation of this accept(SocketImpl) method.

import java.net.ServerSocket;
import java.net.SocketImpl;
import java.net.SocketImplFactory;

/* subclass the SocketImpl class to provide actual implementation of
socket policies */

class MySockImpl extends SocketImpl

private native void socketAcceptMethod(SocketImpl s_imp)
throws IOException;



/* define a factory to generate instances of MySockImpl class*/
class MyFac implements SocketImplFactory


/* A class using server socket and defining its behavior */
public class Server /* end of main() */
} /* end of class Serv */

available()

ClassName

SocketImpl

Purpose

Gets the number of bytes that can be read without blocking.

Syntax

protected abstract int available() throws IOException

Parameters

None.

Description

This method should be defined in the subclass of the SocketImpl class. This returns the number of bytes a socket can read without blocking. This method can be used to read from the input stream of the socket.

Imports

import java.net.SocketImpl;

Returns

The return type of this method is int.

bind(InetAddress, int)

ClassName

SocketImpl

Purpose

Binds the server socket to the specified port on a host specified by the InetAddress.

Syntax

protected abstract void bind(InetAddress inet, int port) throws IOException

Parameters

inet

InetAddress of the host to which the socket should be bound.

port

Port number on the above host to bind the socket to.

Description

This method should be defined in the subclass of the SocketImpl class. After creating a socket instance, this method is invoked to bind the server socket to the specified port on a host.

Imports

import java.net.SocketImpl;

Returns

None.

See Also

The class InetAddress; interface SocketImplFactory; class ServerSocket

Example

This method is used by ServerSocket class to bind to a specified port on a given host. You should write your own native method to implement this method by subclassing the SocketImpl class.

close()

ClassName

SocketImpl

Purpose

Closes the socket connection.

Syntax

protected abstract void close() throws IOException

Parameters

None.

Description

This method should be defined in the subclass of the SocketImpl class. This method is invoked when Socket.close() or ServerSocket.close() is called.

Imports

import java.net.SocketImpl;

Returns

None.

See Also

The class ServerSocket; class Socket; interface SocketImplFactory

Example

Here is an example usage and definition of this method in a subclass of SocketImpl.

import java.net.Socket;
import java.net.SocketImpl;
import java.net.SocketImplFactory;

/* subclass the SocketImpl class to provide actual implementation of
socket policies */

class MySockImpl extends SocketImpl
private native void socketCloseMethod() throws IOException;



/* define a factory to generate instances of MySockImpl class*/

class MyFac implements SocketImplFactory

connect(String, int), connect(InetAddress, int)

ClassName

SocketImpl

Purpose

Use these methods to define the connect method of a client socket if you are providing your own SocketImpl.

Syntax

protected void connect(String name, int port) throws IOException
protected void connect(InetAddress addr, int port) throws IOException

Parameters

name

Name of the host to which the socket is connected.

addr

Address of the host to which the socket is connected.

port

Port number on the host, to which the socket connection is to be established.

Description

These methods should be defined in the subclass of the SocketImpl class. Given the port number and the name or InetAddress of the host machine where a server is available, these methods provide the implementation for the connect() method in Socket class. This method is invoked during construction of a Socket instance, after create() method is invoked.

Imports

import java.net.SocketImpl;

Returns

None.

See Also

The class Socket; interface SocketImplFactory

Example

The following code illustrates an example implementation outline for these methods.

import java.net.Socket;
import java.net.SocketImpl;
import java.net.SocketImplFactory;

/* subclass the SocketImpl class to provide actual implementation of
socket policies */

class MySockImpl extends SocketImpl

private native void socketConnectMethod(String host, int port)
throws IOException;

protected void connect(InetAddress addr, int port) throws
IOException

private native void socketConnectMethod(InetAddress addr, int port)
throws IOException;



/* define a factory to generate instances of MySockImpl class*/

class MyFac implements SocketImplFactory

create(boolean)

ClassName

SocketImpl

Purpose

Creates either a stream socket or a datagram socket.

Syntax

protected abstract void create(boolean is_stream) throws IOException

Parameters

is_stream

The value of this variable should be set to true if you need a stream socket; if you need a datagram socket, this should be set to false.

Description

This method should be defined in the subclass of the SocketImpl class. Depending on the value of the boolean input, either a stream socket or a datagram socket is created. This is used while constructing instances of both Socket and ServerSocket. The default socket created by using the SocketImpl implemented is a stream socket.

Imports

import java.net.SocketImpl;

Returns

None.

See Also

class ServerSocket; class Socket; interface SocketImplFactory

Example

The following example illustrates a sample implementation outline for this create(boolean) method.

import java.net.Socket;
import java.net.SocketImpl;
import java.net.SocketImplFactory;

/* subclass the SocketImpl class to provide actual implementation of
socket policies */

class MySockImpl extends SocketImpl

private native void socketCreateMethod(boolean is_stream)
throws IOException;



/* define a factory to generate instances of MySockImpl class */
class MyFac implements SocketImplFactory

getFileDescriptor()

ClassName

SocketImpl

Purpose

The file descriptor of the socket is returned.

Syntax

protected FileDescriptor getFileDescriptor() throws IOException

Parameters

None.

Description

Each socket has a file descriptor associated with it. It is the way in which the socket is implemented. This method returns a handle to the file descriptor.

Imports

import java.net.SocketImpl;

Returns

The file descriptor associated with the socket.

getInetAddress()

ClassName

SocketImpl

Purpose

Returns the InetAddress of the machine to which the socket is connected.

Syntax

protected InetAddress getInetAddress()

Parameters

None.

Description

A socket connects to a machine and performs its task of communicating with other hosts. The InetAddress associated with the server's host is obtained using this method.

Imports

import java.net.SocketImpl;

Returns

InetAddress representation of the machine to which the socket is connected.

See Also

The class ServerSocket; class Socket; interface SocketImplFactor

getInputStream()

ClassName

SocketImpl

Purpose

An InputStream for this socket is obtained.

Syntax

protected abstract InputStream getInputStream() throws IOException

Parameters

None.

Description

An InputStream for the socket is returned to communicate with the paired endpoint of the point-to-point communication. This method should be defined in the subclass of the SocketImpl class.

Imports

import java.net.SocketImpl;
import java.io.InputStream;

Returns

An instance of InputStream class.

See Also

The class ServerSocket; class Socket; interface SocketImplFactory

Example

The following example illustrates a sample implementation outline for this getInputStream() method.

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

class MySockImpl extends SocketImpl

private native void socketgetInputStreamMethod()
throws IOException;

}

getLocalPort()

ClassName

SocketImpl

Purpose

Returns the local port to which this socket is bound.

Syntax

protected int getLocalPort()

Parameters

None.

Description

Every socket has a corresponding local port to which it has connected. For example, in case of a client, though it has connected to a server socket for service, it has an associated local port to which the server connects and sends a reply.

Imports

import java.net.SocketImpl;

Returns

Port number of the local port.

See Also

The class ServerSocket; class Socket; interface SocketImplFactory

getOutputStream()

ClassName

SocketImpl

Purpose

An OutputStream for this socket is obtained.

Syntax

protected abstract InputStream getOutputStream() throws IOException

Parameters

None.

Description

An OutputStream for the socket is returned to communicate with other sockets. This method should be defined in the subclass of the SocketImpl class.

Imports

import java.net.SocketImpl;

Returns

An instance of OutputStream class.

See Also

The class ServerSocket; class Socket; interface SocketImplFactory

Example

The following example illustrates a sample implementation outline for this getOutputStream method.

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

class MySockImpl extends SocketImpl

private native void socketgetOutputStreamMethod()
throws IOException;
}

getPort()

ClassName

SocketImpl

Purpose

Returns the number representing the server's port to which the client connects.

Syntax

protected int getPort()

Parameters

None.

Description

A client socket connects to a server at a specified port number, on which the server listens for connections. This method returns the number of this port.

Imports

import java.net.SocketImpl;

Returns

The number of the port on which the server is listening; return type is integer.

See Also

class Socket; interface SocketImplFactory

listen(int)

ClassName

SocketImpl

Purpose

The server socket listens for connection from a client for a given amount of time.

Syntax

protected abstract void listen(int time_count) throws IOException

Parameters

time_count

The amount of time server will listen for connection from clients.

Description

This method should be defined in the subclass of the SocketImpl class. This method is invoked during construction of a server socket. After binding to specified host and port, the server (an instance of ServerSocket) listens for connection from clients for a specified amount of time.

Imports

import java.net.SocketImpl;

Returns

None.

See Also

The class ServerSocket; interface SocketImplFactory

Example

A sample outline is given below to illustrate the definition of the listen(int) method in a subclass of SocketImpl class.

import java.net.*;

class MySockImpl extends SocketImpl

private native void socketListenMethod(SocketImpl s_imp)
throws IOException;



/* define a factory to generate instances of MySockImpl class*/
class MyFac implements SocketImplFactory
}

/* A class using server socket and defining its behavior */
public class Server /* end of main() */
} /* end of class Server */

toString()

ClassName

SocketImpl

Purpose

To get a string form of the socket implementation details.

Syntax

public String toString()

Parameters

None.

Description

This method obtains the port number, file descriptor, and address to which socket is connected, as a String. The file descriptor, address, and port number are concatenated into string form within a String object.

Imports

import java.net.SocketImpl;

Returns

The return type of the method is a String containing the port number, file descriptor, and address of the machine which the server is bound to or to which the client is connected.

See Also

The class ServerSocket; class Socket

Example

The following example gives an outline of implementing this method.

import java.net.*;

class MySockImpl extends SocketImpl

private native void sockettoStringMethod()
throws IOException;

}

SocketImplFactory

Purpose

An interface to define a factory for actual SocketImpl instances.

Syntax

public interface SocketImplFactory extends Object

Description

This interface can be used by various socket classes to implement their policies. By subclassing the SocketImpl class and implementing its methods, desired policies for socket implementation can be provided. Then, by using SocketImplFactory to generate instances of the defined SocketImpl class, a server socket and client socket can be implemented. The factory of Socket and ServerSocket should be set to this factory interface, using the setFactory method in those classes. The factory of Socket or ServerSocket can be specified only once. This interface should be defined only if SocketImpl is subclassed.

PackageName

java.net

Imports

import java.net.SocketImplFactory;

Constructors

None.

Parameters

None.

Example

Refer to the example in class SocketImpl.

createSocketImpl()

Interface

SocketImplFactory

Purpose

To generate an instance of SocketImpl that defines the actual socket implementation policies.

Syntax

public abstract SocketImpl createSocketImpl()

Parameters

None.

Description

This method should be used to generate instances of a user-defined SocketImpl subclass. This subclass will implement the socket policies desired by the user. This will be invoked by the Socket or ServerSocket constructors to define their SocketImpl member.

Imports

import java.net.SocketImplFactory;

Returns

This method returns an instance of a subclass of SocketImpl.

See Also

The class SocketImpl

Example

Refer to the example in class SocketImpl.

The Network and Sockets Project: A Client-Server Rendezvous Applet

In the Client-Server Rendezvous applet, a client will contact an existing server and obtain details. You should provide three buttons: clientinfo, serverinfo, and fileinfo. On clicking the clientinfo button, the client will print out its details, the host it is running on, and the port on which it is connected. It should be able to gather the information about the server and print the details when the serverinfo button is pressed. When the fileinfo button is pressed, the client will send a request to the server to obtain the contents of a file residing on the server's side.

The applet should also be a stand-alone application, so that you can run it from a Java environment using the Java interpreter or it can also be launched from a Web browser, supporting Java. The scenario for this applet is illustrated in Figure 10-10. The steps involved are as follows:


Figure 10-10  Sequence of actions in the Client-Server Rendezvous

1.  The server connects to a port on the host, to which it is initialized, and listens for connections from clients.

2.  A client will connect to the server by specifying the hostname and the port on which the server is listening.

3.  The client retrieves the details about itself and displays the information.

4.  The client obtains the information about the server and displays it.

5.  The client sends a request to the server asking for the contents of a file on the server's side.

6.  The server, on receiving the request, opens the relevant file, if it exists, and sends the contents to the client over the socket streams.

7.  The client receives the file contents from the server and displays them.

8.  Once the necessary processing is completed, the streams and sockets are closed appropriately.

You must now be able to implement the applet using the APIs described in this chapter. As you know, any applet for a given specification can be implemented in different ways. One such implementation is provided here. In this implementation, Threads are used on the server's side to process multiple clients. In the given applet, the Server is started on a given machine. The Client can either be run as a stand-alone application using the Java interpreter or launched from a Web browser supporting Java. In either case, the server hostname and port number are passed as arguments to the executable.

Building Your Applet

1.  First create a Server class which should accept connection from clients. Make it a public class and the filename should be Server.java. This class should contain the following members as listed in Table 10-2.

Table 10-2 Members of Server class


Modifier

Type

Variable-name

Purpose


static

ServerSocket

ServSock

An instance of ServerSocket is created to enable the server to accept connections from clients.

static

Socket

theSocket

An instance of Socket that will be created on the Server side when ServerSock is instantiated.

static

int

port

Port number on which the server connects and creates ServerSock

static

ServerThread

client[]

An array of ServerThread objects which will act as servers for every client that connects to the server, so that there is one ServerThread for one client.

After the addition of these members, your file Server.java should contain the following:

// import the necessary classes relevant to the class Server

import java.net.Socket;
import java.net.ServerSocket;
import java.io.*;

Class name: Server


public class Server

2.  Having created the class, now define the main method for the class. Create an instance of ServerSocket after specifying the port number. Then the server waits in a loop for connections from clients. This is done using the accept() method of ServerSocket. After accepting connection from a client, a server thread is spawned for each client. This enables exclusive service to the client by a corresponding server Thread. The start() method of Thread will start the servicing of the server Thread to the client. Adding these functions to your Server class will make the Server.java file contain the following code:

import java.net.Socket;
import java.net.ServerSocket;
import java.io.*;


Class name: Server
This class is run as a background process.
eg., % java Server &

It accepts connection from clients and spawns a server Thread
for every such connection and goes back to listen for more
connections. Maximum of two clients can be active at a given
instant. Processing of client requests is done by the
corresponding server thread.


public class Server
else
System.out.println('Rejected a
connection');
}
} catch (IOException ioE)
}

3.  Now you have the necessary code for a Server to run. Next, you should write the necessary code for implementing the ServerThread the Server spawns for every Client. Create a public class ServerThread. It should be a subclass of Thread class in Java and should contain the members specified in Table 10-3.

Table 10-3 Members of ServerThread class


Modifier

Type

Variable name

Purpose


Socket

mySocket

This Socket object will be the socket instance on Server's side for a connected Client. This is passed on to this ServerThread using the constructor.

int

myId

Every ServerThread has an Id associated with it, which also identifies the Client. There can be only one ServerThread with a given Id, at a given instance.

DataInputStream

datain

DataInputStream associated with every ServerThread (which will be the Client's OutputStream) to receive messages from the Client.

DataOutputStream

dataout

DataOutputStream associated with every ServerThread (which will be the Client's InputStream) to send messages to the Client.

With these data members and the constructor for the ServerThread class, your ServerThread.java should now contain the following:

import java.net.Socket;
import java.io.*;
import java.awt.*;

Class name: ServerThread

This class subclasses the Thread class. This thread is spawned by
the Server object, that accepts connection from clients.
Each ServerThread services requests from one client assigned by
the Server


public class ServerThread extends Thread

4.  Now you should override the run() method of Thread class in ServerThread class. Assuming you have a function processRequests() in this class, the run method will call the processRequests() while there are more requests from the Client. In the meantime, after processing every request, the Thread should yield to the other ServerThreads to process their respective Client requests. After all the requests are processed, you should close the sockets and streams that are open. Enter the following method into the ServerThread class.

/**
The 'run' method of Thread class being implemented here


public void run() catch (IOException E)
}

/** clean up when done */

void CleanUp()
}

5.  Let retrieving the contents of a requested file be a service provided by the ServerThread. When the ServerThread receives a message "File" from a Client through the DataInputStream, it understands that the Client is requesting a file to be retrieved and it expects another message from the Client indicating the name of the file to be retrieved. The ServerThread then reads the file and sends its contents using the DataOutputStream. If the message is "Bye", the ServerThread understands that the Client intends to close the session and so the method returns false. This makes the ServerThread's run() method terminate and so the ServerThread gets disposed. To achieve the described effect, include the following processRequests() method, whose return type is boolean. This method assumes the existence of a GetFile() method in this class.

/** This method processes client requests */

private boolean processRequests() throws IOException
else if (req.equals('Bye'))
return false;
else
} catch(IOException ioe)
}

6.  As a final part of our ServerThread class, you should now implement the GetFile() method. Given a filename, this method will first check to see if the file exists and if it does, whether it is readable. Then using the file, the method creates a DataInputStream by passing the FileInputStream as a parameter. Next the method reads the file line-by-line and sends the line contents to the Client using the DataOutputStream object named dataout. It follows the file contents with an EndOfFile message to the Client. Add the following code into the ServerThread class.


Method that retrieves contents of a file the client is
interested in. It uses FileInputStream to achieve the same */


private void GetFile(String file_name)
dataout.writeUTF('EndOfFile');
dataout.flush();
} catch (IOException ioE)
}

7.  The Client class is the next one to be created. Client is the class that will be launched as an applet from the Web browser. So it extends the applet and in this implementation, implements the Runnable interface. It acts as a client requesting service from an existing Server. According to the specification, this should also run as a stand-alone application. It has instances of Socket, DataInputStream, DataOutputStream, and Thread as its members. It should also implement user interface with three buttons: clientinfo, serverinfo and fileinfo. Enter the following code in the file Client.java.

import java.net.*;
import java.io.*;
import java.applet.*;
import java.awt.*;


Classname: Client
This is a class that creates a client socket, Socket, and
retrieves information about
client Host or
server Host or
requests a File from the server

Illustrates the usage of APIs in the classes
java.io.InetAddress
java.io.Socket



public class Client extends Applet

8.  You should override the init() method of Applet class by creating a Panel with three buttons. Then the Client connects to an existing Server at a specified host and port. It also obtains the input and output streams. If the client is an applet, it can also obtain some of the parameters from the HTML file. The following init() method implements these specifications. Include this method in the Client class.

public void init()

makeConnection(); // establish connection



private void makePanel()

private void makeConnection() catch (IOException E)

9.  To implement this as a stand-alone application you need to write a method main(). The following code listing implements this method, which obtains the server name and port number from the command line. An instance of Client is created and a method myinit() is invoked to pass the parameters to the Client object. Then the Client Thread is started and a Frame is initialized to contain the three buttons to be created. Enter the following code in the Client class to extend it as a stand-alone application.

public static void main(String args[]) throws IOException

public void myinit(String Host, int port)

10.  Now that you have Buttons in the Panel, you have to override the action() method so that appropriate action is taken when a button is pressed. The following code achieves this. Enter the code in the class Client. Also include two variables, InpStr and count. InpStr is an array of String that will contain the string to be printed on the canvas. The variable count will keep track of the lines printed out to the canvas.

String InpStr[];
int count;

/** Action for Button event */
public boolean action(Event evt, Object arg)
else if('serverinfo'.equals(arg))
else if('fileinfo'.equals(arg)) catch (ArrayIndexOutOfBoundsException a)
printOut('nn'); // a pretty print method available
within this class
}
}
return true;

11.  Information about the Client is to be retrieved when the clientinfo button is pressed. Including the following method in Client class will make this happen. If the InetAddress of the local host is made available, then more details can be obtained from the InetAddress instance that will reflect the client machine information.

/** Method to obtain information about the client host */

public void ClientInfo() catch (IOException ioE);

12.  Server details can be obtained from the server's InetAddress in a similar manner as from the Client's. To get the InetAddress of the server, the Socket instance is used. The getInetAddress() method of Socket class is used. Include the following code in the Client class.

/** Method to obtain information about the server */

public void ServerInfo()

13.  The following MakeRequests() method is used to send the file name to the server and request the contents of the file. The client then reads the reply from the server and prints it on the screen until the end of file is reached. The datain and dataout members of type DataInputStream and DataOutputStream are used by the Client to communicate with the Server.

/** Client makes its requests to the server by sending messages
over sockets
Remote File retrieval is done in this method


public void MakeRequests(String fil_n)
dataout.writeUTF('Bye'); // transaction is complete
dataout.flush();
} catch (IOException ioE);

14.  Include the following methods in the class Client. To print the strings on the canvas in an orderly manner, write the printOut() method, which is used by other methods to print on the canvas. The paint() method is overridden here to write to the exact locations on the canvas.

/** Method to print the obtained strings to output stream


public void printOut(String str) catch (InterruptedException ie);




* Paint it.


public void paint(Graphics g)

15.  You should take necessary care to close any open files, streams, or sockets. This can be done in the stop() method of the Applet, which is called when the Applet is terminated.

/* Applet stop */
public void stop() catch (IOException E);
}

16.  The above three files are compiled using javac. The server is executed using the Java interpreter. Use

java Server


at the command prompt to run the Server.

17.  The Client applet can be launched from the Web using the following HTML file, csr.html.

<title> Client-Server Rendezvous </title>
<hr>
<applet code=Client.class width=600 height=400>
<param name=servHost value='serval.cat.syr.edu'>
<param name=servPort value=3001>
</applet>
<hr>

The applet, when launched, using the command appletviewer csr.html, will create a Panel that will appear as in Figure 10-11. When you press any of the three keys, appropriate action is taken and details are printed on the canvas. This applet implements the Client-Server Rendezvous and exchange of information between the Client and the Server. This illustrates a typical client-server application.


Figure 10-11  Client-Server Rendezvous applet in action

How It Works

The project developed in this chapter is a client-server application. The server is a stand-alone application. First, start the server on the host you want to run the server. In the code, we had the host named as serval.cat.syr.edu. If the host you are running your server on is foo.bar.usa, change the string serval.cat.syr.edu in the csr.html file to foo.bar.usa. After starting the server, run the client applet. When the applet comes up, it displays a window with three buttons: clientinfo, serverinfo, fileinfo. If you click the clientinfo button, the details of the host, on which the client applet is executed, is displayed on the canvas. If you click the serverinfo button, the details of the server host, host on which the server is running, is displayed on the window. Whereas if you click on the fileinfo button, the contents of the /etc/motd file (in case of Unix systems) is displayed on the screen. If you are interested in any other file, change the filename in the code to the desired filename. As an exercise, change the code such that the filename is passed as a parameter from the command line prompt (in case of stand-alone application) or from the HTML file (in case it's launched from a browser). This project gives you a good start in developing networking applications in Java. Happy networking!



Politica de confidentialitate | Termeni si conditii de utilizare



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 947
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved