Java Reference
In-Depth Information
import
java.io.OutputStream;
public class
SocketProxy
implements
MarketProxy {
// the socket and the associated in and out streams
private
Socket socket;
private
InputStream in;
private
OutputStream out;
// the name of the host where the market server runs
private
String host;
public
SocketProxy(String host){
this
.host
#
host;
}
// send a synchronous message to the market
// server and returns the reply
private
String sendMessage(String request)
throws
Exception {
out.write((request
!
"\n").getBytes());
out.flush();
byte [] buffer
#
new
byte[1024];
int
en;
len
#
in.read(buffer);
String reply
#
new
String(buffer,0,len);
return
reply;
}
// connect to the market server providing the employee
// code and pwd the server authenticates the employee
public
String connect(
long
employee, String password)
throws
Exception{
socket
#
new
Socket(host,Const.SERVER_PORT);
in
#
socket.getInputStream();
out
#
socket.getOutputStream();
String reply
#
sendMessage(Const.AUTHENTICATE
!
" "
!
employee
!
" "
!
password);
if
(reply.startsWith(Const.OK)){
return
reply.substring(Const.OK.length());
}
else
{
return null
;
}
}
// return the name of a product given the code
public
String getName(
long
item) throws Exception {
String reply
#
sendMessage(Const.GET_NAME
!
" "
!
item);
if
(reply.startsWith(Const.OK)){
return
reply.substring(Const.OK.length());
}
else
{