Friday, September 10, 2010 10:39:19Login · Register
 

    Challenge Activity
09:22:09 - l0gan_l135
     - Completed real [2]
07:42:10 - l0gan_l135
     - Completed real [3]
05:55:17 - aspen_23
     - Completed recon [1]
02:27:21 - GemaRastem
     - Completed basic [2]
02:26:21 - GemaRastem
     - Completed basic [1]
02:21:00 - GemaRastem
     - Completed recon [3]
01:55:39 - GemaRastem
     - Completed recon [2]
01:43:45 - GemaRastem
     - Completed recon [1]
01:31:59 - veerendragautam2009
     - Completed decrypt [3]
01:26:45 - veerendragautam2009
     - Completed decrypt [2]
01:25:16 - veerendragautam2009
     - Completed decrypt [1]
12:31:00 - veerendragautam2009
     - Completed basic [1]
12:26:04 - veerendragautam2009
     - Completed recon [6]
11:13:29 - veerendragautam2009
     - Completed recon [3]
10:59:23 - veerendragautam2009
     - Completed recon [1]
09:30:05 - sirEgghead
     - Completed real [4]
 

    Scoreboard Top 20
UserPoints
Abhineet4795   
auditorsec4795   
ne0114795   
Null Set4795   
blandyuk4780   
bluechill4750   
Teddy4730   
TurboBorland4475   
Qwexotic4460   
tiiger11114205   
preet4180   
LiquidFusi0n4175   
OnlyHuman4125   
samthg4110   
satishek3900   
pilchdragon3660   
Override3655   
chronic123640   
sirEgghead3625   
dash803590   
 

    Login
Username

Password



Not a member yet?
Click here to register.

Forgotten your password?
Request a new one here.
 

    Users Online
· Guests Online: 8

· Members Online: 1
dudexxl

· Members on IRC: 10
Xires, TurboBorland, ryan1918, Polynomial, louve, LK, IFailStuff, epoch_qwert, connection, bubatime

· Bots Online: 1
GoogleBot

· Total Members: 1,491
· Newest Member: elostaz3omda
 

 

 

 

    Top 10 Forum Posters
UserPosts
bluechill918   
Qwexotic699   
cruizrisner487   
Null Set363   
TurboBorland335   
madf0x311   
Stormc1nd3r308   
auditorsec302   
Override238   
jakecrepinsek235   
 

    Affiliates
 

TCP based client/server (2/2)
(This will be easyer to understand if you have prior knowledge of OOP and THREADS)
The client program costs of two classes...

Client.Main.java

This is where the connection is to the server is started, the user input for the user name is taken and commands to the client are being awaited.

Download source  GeSHi: Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 
package client;
 
//IO imports
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
/**
 *
 * @author Killordie
 */
public class Main
{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        //Show server name and version.
        System.out.println("Killordie's server");
        System.out.println("Version 1.0.0 \n");
        
        try
        {
            //Show "look good" start up messages
            System.out.println("Booting up the client...\r\n");
            Thread.sleep(1000);
 
            System.out.println("Please fill in your desired username:");
            //Create a new BufferedReader and Client object with the given input for the username.
            BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
            Client client = new Client(userInput.readLine());
 
            //Attempt to connect to the server.
            System.out.print("\r\n");
            client.Connect("127.0.0.1", 3333);
 
            //Loop for commands untill the client has been asked to shut down.
            client.SendCommand();
        }
        catch (Throwable error)
        {
            System.out.println(error.getMessage());
        }
    }
 
}
 
Parsed in 0.070 seconds, using GeSHi 1.0.8.6


Client.Client.java

Makes the socket connection, holds all the commands, loops till the shut down signal is given.
(You might want to create a seperate class just for the commands.)

Code

package client;

//IO imports
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
//Socket imports
import java.net.Socket;

/*
 * This connection class will manage all client connections to the server as well as sending a message back and fort to make sure the connection is working propperly.
 * The class extends from Thread since we will need to create a seperate thread awaiting connections.
 * @author Killordie
 */
public class Client
{
    //Server attributes
    private String serverip;
    private int serverport;
    private String username;

    //Client attributes
    public Socket clientSocket;
    private PrintWriter writer;
    private BufferedReader reader;
    private boolean isConnected = false;
    private boolean shutdown = false;

    /**
     * Constructor, set the username available to the rest of the class.
     * @param username The username for the client to connect with to the server.
     */
    public Client(String username)
    {
        this.username = username;
    }

    /**
     * Returns a flag telling if the client is connected or not.
     * @return boolean isConnected Connected true or false.
     */
    public boolean isConnected()
    {
        return isConnected;
    }

    /**
     * Returns a flag telling the client to shut down yes or no.
     * @return boolean shutdown Shut down the client.
     */
    public boolean isShutdown()
    {
        return shutdown;
    }

    /**
     * Return the buffereader for the client.
     * @return bufferedreader reader The clients buffered reader.
     */
    public BufferedReader getReader()
    {
        return reader;
    }

    /**
     * Connect to the specified server using the given ip and port number.
     * @param serverip String The server IP (domain name not supported).
     * @param serverport int The port number to connect on.
     */
    public void Connect(String serverip, int serverport)
    {
        this.serverip = serverip;
        this.serverport = serverport;

        try
        {
            clientSocket = new Socket(this.serverip,this.serverport); //Create the socket and connect to the give IP and  PORT
            reader   = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); //Prepare the buffer to read out information
           
            System.out.println("Connecting to the server...");
            Thread.sleep(1000);

            //Retrieve message from the server and print this to the screen.
            String serverReply = reader.readLine(); 
            System.out.println(serverReply);

            //Pass your username on to the server for remote display.
            writer = new PrintWriter(clientSocket.getOutputStream(), true);
            writer.println(this.username);

            //We made it this far why not turn the flag telling the rest of the client we have estebalished a connection
            isConnected = true;
        }

        catch (Throwable e)
        {
            System.out.println(e.getMessage());
        }
    }

    /**
     * Send a command to the server console.
     */
    public void SendCommand()
    {
        System.out.println("\r\nType '/help' for a list of possible commands:");
        System.out.print("> ");
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

        try
        {
            //Loop through the commands as long as the shutdown is not given.
            while (this.shutdown == false)
            {
                String message = input.readLine();
                int command = ExecuteCommand(message);
 
                switch (command)
                {
                    //help
                    case 0:
                    {
                        this.CommandHelp();;
                        break;
                    }
                    //info
                    case 1:
                    {
                        this.CommandInfo();
                        break;
                    }
                    //shutdown
                    case 2:
                    {
                        this.CommandClose();
                        break;
                    }
                    //Wrong command given
                    default:
                    {
                        System.out.println("The command " + message + " was not reconized by the server.");
                        break;
                    }
                }
                Thread.sleep(400);
            }
        }

        catch (Throwable a)
        {
            a.getCause();
        }
    }

    /**
     * Execute the actuall command and return a int for the command switch case in SendCommand.
     * @param input String
     * @return int
     */
    private int ExecuteCommand(String input)
    {
        String[] commands = {"/help", "/info", "/shutdown"};
        int i = 0;

        for (String command : commands)
        {
            if (input.startsWith(command))
            {
                return i;
            }
            i++;
        }

        return 999999999;
    }

    /**
     * Display all commands available to you.
     */
    private void CommandHelp()
    {
        System.out.println("\r\nThe current client commands are:");
        System.out.println("/help           - Displays all the possible client commands.");
        System.out.println("/info           - Gets the connection info from your socket.");
        System.out.println("/shutdown       - Shuts down the client and closes the socket.\r\n");
    }

    /**
     * Get the socket info such as the Server IP you are connecting to, your IP and the socket number which are using.
     */
    private void CommandInfo()
    {
        System.out.println("You are " + this.username + ", connected via IP: " + this.clientSocket.getLocalSocketAddress() + " to server IP " +  this.clientSocket.getInetAddress() );
    }

    /**
     * Close the complete socket and anything that goes with it.
     */
    private void CommandClose()
    {
        try
        {
            //Write on close
            System.out.println("\r\nClosing connection to the server...");
            Thread.sleep(1000);

            //Close and reset everything
            clientSocket.close();
            reader.close();
            writer.close();
            this.shutdown = true;
            this.isConnected = false;
        }

        catch (Throwable e)
        {
            System.out.println(e.getMessage());
        }
    }
}



Comments
 
No Comments have been Posted.
 
 
Post Comment
 
Please Login to Post a Comment.
 
 
Ratings
 
Rating is available to Members only.

Please login or register to vote.

Awesome! Awesome! 0% [No Votes]
Very Good Very Good 100% [1 Vote]
Good Good 0% [No Votes]
Average Average 0% [No Votes]
Poor Poor 0% [No Votes]