import java.net.*;
import java.io.*;
public class Serverdemo {
public static void main(String[] args) throws IOException {
int port = 8888;
ServerSocket serverSocket = null;
Socket clientSocket = null;
ClientThread slave = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + port + ".");
System.exit(1);
}
try {
while (true)
{ try { clientSocket = serverSocket.accept(); }
catch (IOException e)
{ System.err.println("Accept failed.");
System.exit(1); }
slave = new ClientThread (clientSocket);
slave.start ();
}
} finally { serverSocket.close(); }
}//main close
}//serverthread class close
class ClientThread extends Thread
{
Socket clientSocket = null;
//gives this thread a new port so the server can still listen on the original port
public ClientThread (Socket clientSocket)
{ this.clientSocket = clientSocket; }
public void run ()
{
BufferedReader clientIn = null;
PrintWriter clientOut = null;
InputStreamReader clientReady = null;
try {
clientIn = new BufferedReader ( new InputStreamReader(clientSocket.getInputStream() ) );
clientOut = new PrintWriter(clientSocket.getOutputStream(), true);
clientReady = new InputStreamReader(clientSocket.getInputStream() );
} catch (IOException e) {
System.err.println("Could not I/O Client Socket");
System.exit(1);
}
//clientIn, clientOut
try {
String inputLine, outputLine;//these var names suck
String Username; //outputLine will be mostly for errors
clientOut.println("Welcome to SMART CHAT, What is your Chat Name?");
Username = clientIn.readLine();
//perform the validation tests!
System.out.println(Username + " is trying to Log On");
clientOut.println(Username); //send the user their name
do{
do{
if(clientReady.ready()) //if client's typing
{ break; //break the wait loop
}else{
MyTimer.timeFor(250);//a quarter second wait
}
}while(true);
inputLine = clientIn.readLine(); //server thread gets client message
if(inputLine.equals("/USER SENDING")) //the only way they can enter a message or command
{
outputLine = clientIn.readLine();
if(inputLine.equals("/LOG OFF"))
{
clientOut.println("LOG OFF");
clientOut.close();
clientIn.close();
clientSocket.close();
}
else if(outputLine.equals("/HELP"))
{}
else if(outputLine.equals("/DEMO"))
{}
else
{
clientOut.println("Server got: " + outputLine);
}
}//if close
}while(true);
} catch (IOException e){
System.err.println("I/O problems");
System.exit(1);
}
}//run
}//class close
class MyTimer
{
//pauses for the "duration" in milliseconds
public static void timeFor(int duration)
{
long timer;
long starttime;
starttime = System.currentTimeMillis();
do{
timer = System.currentTimeMillis();
}while( (timer - starttime) < duration);
}
}