| 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.
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.)
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.
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());
}
}
}
Please Login to Post a Comment.
Rating is available to Members only.
Please login or register to vote.
Please login or register to vote.
| Awesome! | 0% | [No Votes] | |
| Very Good | 100% | [1 Vote] | |
| Good | 0% | [No Votes] | |
| Average | 0% | [No Votes] | |
| Poor | 0% | [No Votes] |


