FileDocCategorySizeDatePackage
SimpleServer.javaAPI DocExample2287Thu Oct 05 17:25:14 BST 2000None

SimpleServer.java

//Source code for SimpleServer.java

//loads classes required in this program 
import java.io.*;
import java.net.*;

public class SimpleServer
{
 public static final int DEF_PORT = 8765;
 
 private static ServerSocket listenSocket;
	
 public static void main(String[] args)
 {

 try
 {
	//ServerSocket establishes the port where server waits for connections
	listenSocket = new ServerSocket(DEF_PORT);
 }
 
 catch(IOException ex)
 {
	System.out.println("Connection failed on port" + DEF_PORT);
	System.out.println("Exiting............");
	System.exit(0);
 }

 System.out.println("\nServer initalised");
				
 try
 {
	//creates a socket and waits here until a connection request is received
	Socket soc = listenSocket.accept();
	System.out.println("Connection established");
			
	//create an input and output stream for new connection
	PrintWriter outStream = new PrintWriter(new OutputStreamWriter(soc.getOutputStream()));
	BufferedReader inStream = new BufferedReader(new InputStreamReader(soc.getInputStream()));
	
	 //loop forever receiving and replying to messages			
	while(true)
	{

		//waits here until a line of text is received from client
		String linerec = inStream.readLine();

		if(linerec != null)
	 	{	System.out.println("----------------------------------");
			System.out.println("\nReceived: " + linerec);
				
			//when client sends 'quit' command terminate server. 
			if (linerec.compareTo("quit")==0)
			{
				System.out.println("\nReceived Exit Command from client");
				System.out.println("\nExiting...........\n");
				//close socket
				soc.close();
				//terminate program
				System.exit(0);			
			}
			
			//send string back to client
			outStream.println(linerec);
			outStream.flush();			
			
			System.out.println("Sent: " + linerec);
		}
	
		else
		{
			System.out.println("Client is not responding");
			soc.close();
			System.out.println("Exiting....");
			System.exit(0);
		}
			
	}//end of while(true)
			
 }//end of try
 
 //catchs if connection is terminated
 catch(IOException ex)
 {
	System.out.println("Connection terminated");
	System.out.println("Exitting......");
	//terminates program
	System.exit(0);
 }

 }//end of main
	
}//end of SimpleServer