import java.net.*;
import java.io.*;

/**
 * A Socket that uses the SFP protocol
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison University
 */
public class SFPServerSocket extends ServerSocket
{

    /**
     * Default Constructor
     */
    public SFPServerSocket() throws IOException
    {
       super(SFPConnection.DEFAULT_PORT);
    }



    /**
     *  Listens for a connection to be made to this socket and 
     *  accepts it. The method blocks until a connection is made. 
     */
    public Socket accept() throws IOException
    {
       boolean            ok;
       byte[]             initial;  
       int                i, len;
       SFPInputStream     in;
       SFPOutputStream    out;
       SFPSocket   socket;


       socket = new SFPSocket();
       // Complete the connection (see the javadocs)
       implAccept(socket);

       // Start the server side of the sign-on process
       in =  (SFPInputStream)socket.getInputStream();
       out = (SFPOutputStream)socket.getOutputStream();

       // Read the initial message from the client
       initial = new byte[9];
       in.read(initial);

       // Check the initial message and reply
       ok = true;
       i = 0;
       while ( (i < initial.length)) 
       {
          if (initial[i] != SFPConnection.sfpon[i]) ok = false;
          i++;
       }
	
       if (ok) out.writeSIGNON();
       else    throw(new IOException("No SFPON from client"));

       return socket;
    }


}
