import java.io.*;
import java.net.*;
import java.util.*;
import java.util.Scanner;
public class Server{
static Socket clientSocket = null;
static ServerSocket serverSocket = null;
static String responseLine;
public static boolean stillServ = false;
public static Scanner scanner;
static clientThread t[] = new clientThread[10];
public static void main(String args[]) {
// The default port
int port_number=4444;
if (args.length < 1)
{
System.out.println("Starting game server...\nPort number: "+port_number);
Scanner scanner = new Scanner(System.in);
} else {
port_number=Integer.valueOf(args[0]).intValue();
}
try {
serverSocket = new ServerSocket(port_number);
System.out.println("\n**********************\n*** SERVER STARTED ***\n**********************\n");
}
catch (IOException e)
{System.out.println(e);}
System.out.print("Enter a command: ");
String password = scanner.nextLine();
if (password.equalsIgnoreCase("secret")) {
System.out.println("Welcome to Java Application");
}
while(true){
try {
clientSocket = serverSocket.accept();
System.out.println("*** SOMEONE CONNECTED ***\n");
for(int i=0; i<=9; i++){
if(t[i]==null)
{
(t[i] = new clientThread(clientSocket,t)).start();
break;
}
}
}
catch (IOException e) {
System.out.println(e);}
}
}
}
class clientThread extends Thread{
BufferedReader is = null;
PrintStream os = null;
Socket clientSocket = null;
clientThread t[];
Random roll = new Random();
public clientThread(Socket clientSocket, clientThread[] t){
this.clientSocket=clientSocket;
this.t=t;
}
public void run()
{
String line;
String name;
int py;
try{
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
int px = roll.nextInt(200);
//os.println("Enter your name.");
name = "Guest #" + roll.nextInt(6);
System.out.println(name+" has entered the game. Their attack: " + px);
for(int i=0; i<=9; i++)
if (t[i]!=null && t[i]!=this)
t[i].os.println("*** A new user "+name+" entered the chat room !!! ***" );
while (true) {
line = is.readLine();
if(line.startsWith("/quit")) break;
for(int i=0; i<=9; i++)
if (t[i]!=null) t[i].os.println("<"+name+":"+px+"> "+line); // someone said something
}
for(int i=0; i<=9; i++)
if (t[i]!=null && t[i]!=this) {
System.out.println("\n" + name + " has left!\n");
t[i].os.println("*** The user "+name+" is leaving the chat room !!! ***" );
}
os.println("*** Bye "+name+" ***");
for(int i=0; i<=9; i++) {
if (t[i]==this) t[i]=null;
System.out.println("\nSomeone has left!\n");
}
is.close();
os.close();
clientSocket.close();
}
catch(IOException e){};
}
} |