can anyone help me with it??
The following simple server uses the Java Socket API for communication. After a socket connection is established between a client and this server, the server expects the client to send an instance of class Message to the server. Class Message provides two methods: (a) boolean saysExit() allows to test whether the client has sent “exit” and (b) getMessage() returns the message string conveyed by the message object in uppercase.
import java.io.*;
import java.net.*;
public class Server
{
public static void main ( String args[] )
throws IOException, ClassNotFoundException
{
ServerSocket listener
= new ServerSocket ( Integer.parseInt(args[0])) ;
Socket client = listener.accept() ;
ObjectOutputStream out =
new ObjectOutputStream(client.getOutputStream());
ObjectInputStream in =
new ObjectInputStream(client.getInputStream());
while ( true )
{
Object receivedObject = in.readObject();
if (receivedObject instanceof Message)
{
if ( ((Message) receivedObject).saysExit() )
// stop server
break ;
else
// echo back message in uppercase
out.writeObject (
((Message)receivedObject).getMessage().toUpperCase() ) ;
}
else
System.exit(-1) ;
}
out.writeObject( "exit" );
client.close();
}
}
public class Message
{
private String message = null ;
public Message ( String m )
{
message = m ;
}
public String getMessage() { return message ; }
public boolean saysExit() { return message.matches( "exit" ) ; }
}
QuESTIONS...
1. Write a class Client that interacts with the server: the client should (a) establish a socket connection to the server, (b) create input/output streams from/to the server, © create a separate input stream that reads from standard input, and (d) should contain code that reads text typed in at the command line, creates a Message object, sends this object to the server and reads the reply of the server from the corresponding stream. The client should operate in this fashion until the user types “exit” at the command line.
2. Suggest changes to class Server above so that multiple clients can connect to the server at the same time.
Edited by ZekeDragon, 26 May 2011 - 08:06 PM.
Please use [CODE] tags (the # button) when posting code.


Sign In
Create Account

Back to top









