Java Reference
In-Depth Information
The constant
SERVER_PORT
identifies a port on the server to which the clients must make the
connection. For instance, the port for the HTTP protocol is 80. If a server must serve more than
one client at once, it creates a new thread for each connection. Typically a server has a loop that
accepts new connections and then creates a new thread.
The client program that connects to the server is as follows:
Socket socket
#
new
Socket(SERVER_HOST,SERVER_PORT);
InputStream in
#
socket. getInputStream();
OutputStream out
#
socket. getOutputStream();
The constant
SERVER_HOST
is the name (e.g. www.polito.it) or IP address of the server and the
SERVER_PORT
specifies the address to which it is connected.
Since there are several components residing on distributed nodes of the
network and communicating with each other, it is important for them to
share a common set of communication conventions. Such conventions can
be implemented as a set of constants that for simplicity of use we collect in
a single class. Compared with the use of immediate values, the use of con-
stants is less error prone and provides a single point of modification when-
ever a change is to be made.
package Market;
public class
Const {
// TCP connection parameters
public final static
int SERVER_PORT
#
1971;
public final static
String SERVER_HOST
#
"localhost";
// protocol commands
public final static
String OK
#
"OK";
public final static
String ERROR
#
"ERROR";
public final static
String GET_NAME
#
"GET_NAME";
public final static
String GET_PRICE
#
"GET_PRICE";
public final static
String GET_CUSTOMER
#
"GET_CUSTOMER";
public final static
String AUTHENTICATE
#
"AUTH";
public final static
String BUY
#
"BUY";
public final static
String END
#
"END";
public final static
String ABORT
#
"ABORT";
public final static
String QUIT
#
"QUIT";
}
Class
SocketProxy
implements the terminal side of the communication
protocol. All the messages are sent through the method
sendMessage()
that
receives the message to be sent as an argument and returns the reply
received from the server. Since the protocol is synchronous this method
sends the message and waits for the reply.
package
Counter;
import
Market.Const;
import
java.net.Socket;
import
java.io.InputStream;