// =======================================================================
//
// Java network server.
//
// A simple server that always answers the clients requests and loops
// forever.
//
// CS 440 Example
// Harkin, 8.99
//
// ========================================================================
import java.io.*;
import java.net.*;
public class Server
{
static final int DEFAULT_PORT = 9999;
static final int BUFLEN = 80;
// Main
static public void main (String [] argv)
{
int port;
ServerSocket server_sock;
Socket conn_sock;
OutputStream out_stream;
InputStream in_stream;
DataOutputStream dout_stream;
String msg = new String ("Message Received");
char ch;
System.out.println ("Java server starting - whoo, whoo");
try
{
// Set up the desired port
if (argv.length > 0)
port = Integer.parseInt (argv [0]);
else
port = DEFAULT_PORT;
// Create a server socket object and output a message.
server_sock = new ServerSocket (port, 10);
System.out.println ("Server socket open " + server_sock.toString());
// Loop getting the input from the client and sending back a
// message.
while (true)
{
// Wait for a client to connect and return the client socket.
conn_sock = server_sock.accept ();
System.out.println ("Connected " + conn_sock.toString ());
// Get the associated streams so that I/O can take place
// with the client.
in_stream = conn_sock.getInputStream ();
out_stream = conn_sock.getOutputStream ();
dout_stream = new DataOutputStream (out_stream);
// Get a message from the client and output to the screen
System.out.print ("From the client -> ");
while ((ch = (char) in_stream.read ()) != '\n')
{
System.out.print (ch);
}
System.out.println ();
// Send back a response
System.out.println ("Sending the response");
dout_stream.writeChars (msg);
// Close the socket for this client.
conn_sock.close ();
} // end while
} // end try
catch (IOException e1)
{
System.err.println ("Error starting connection\n" + e1.toString());
System.exit (1);
}
// If somehow it terminates, clean up and say so.
finally
{
System.out.println ();
System.out.println ("Server terminates");
}
} // end main
} // end Server