Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

exercice1 #3

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .classpath
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path=""/>
<classpathentry combineaccessrules="false" kind="src" path="/OCSF"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/5"/>
<classpathentry kind="output" path=""/>
</classpath>
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/ClientConsole.class
/EchoServer.class
/ServerConsole.class
/ServerConsoleTest.class
17 changes: 17 additions & 0 deletions .project
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>simpleChat</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
Binary file added ClientConsole.class
Binary file not shown.
59 changes: 42 additions & 17 deletions ClientConsole.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,21 @@ public class ClientConsole implements ChatIF
* @param host The host to connect to.
* @param port The port to connect on.
*/
public ClientConsole(String host, int port)
{

public ClientConsole(String loginID,String host, int port)
{
try
{
client= new ChatClient(host, port, this);


client= new ChatClient(loginID, host, port, this);
}
catch(IOException exception)
{
System.out.println("Error: Can't setup connection!"
+ " Terminating client.");
System.out.println("Error: Can't setup connection!"+ " Terminating client.");


client.connectionClosed(); //when connection is not possible


System.exit(1);
}

Expand Down Expand Up @@ -118,18 +121,40 @@ public void display(String message)
public static void main(String[] args)
{
String host = "";


try
{
host = args[0];

//the port number
int port=0;

//the login id
String loginID="";
try {
loginID = args[0];
}
catch (ArrayIndexOutOfBoundsException e) {
System.err.println("No login ID provided!");
System.exit(1);
}
catch(ArrayIndexOutOfBoundsException e)
{
host = "localhost";

try {
host = args[1];

} catch (ArrayIndexOutOfBoundsException e) {
host = "localhost";

}
ClientConsole chat= new ClientConsole(host, DEFAULT_PORT);
chat.accept(); //Wait for console data
try{
port= Integer.parseInt(args[2]); //convert argument in int
}catch(ArrayIndexOutOfBoundsException e){
port=DEFAULT_PORT; //if exception from using arguments, use default port
}
catch(NumberFormatException ne) { //we check that it works for any other format
port=DEFAULT_PORT;
}

ClientConsole chat=new ClientConsole (loginID, host,port);
chat.accept(); //Wait for console data

}

}
//End of ConsoleChat class
Binary file added EchoServer.class
Binary file not shown.
200 changes: 164 additions & 36 deletions EchoServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
// license found at www.lloseng.com


import java.io.*;
import client.ChatClient;
import ocsf.server.*;


/**
* This class overrides some of the methods in the abstract
* superclass in order to give more functionality to the server.
Expand All @@ -18,12 +21,18 @@
public class EchoServer extends AbstractServer
{
//Class variables *************************************************

final private String key="loginKey";

/**
* The default port to listen on.
*/
final public static int DEFAULT_PORT = 5555;

//I add
ChatClient client;


//Constructors ****************************************************

/**
Expand All @@ -34,6 +43,14 @@ public class EchoServer extends AbstractServer
public EchoServer(int port)
{
super(port);

try{
listen(); //Start listening for connections
}
catch (Exception ex){
System.out.println("ERROR - Could not listen for clients!");
}

}


Expand All @@ -45,13 +62,82 @@ public EchoServer(int port)
* @param msg The message received from the client.
* @param client The connection from which the message originated.
*/
public void handleMessageFromClient
(Object msg, ConnectionToClient client)
{
System.out.println("Message received: " + msg + " from " + client);
this.sendToAllClients(msg);
public void handleMessageFromClient(Object msg, ConnectionToClient client) {
System.out.println("Message received: " + msg + " from " + client);
String msgStr=(String)msg;
if(msgStr.startsWith("#login")) {
String loginID="";
client.setInfo(key, loginID);
}
else {
this.sendToAllClients(msg);
}


String message = msg.toString();
if (message.startsWith("#")) {
String[] params = message.substring(1).split(" ");
if (params[0].equalsIgnoreCase("login") && params.length > 1) {
if (client.getInfo("username") == null) {
client.setInfo("username", params[1]);
} else {
try {
client.sendToClient(("Your username has already been set!"));
} catch (IOException e) {
//error sending
}
}
}
} else {
if (client.getInfo("username") == null) {
try {
client.sendToClient(("Please set a username before messaging the server!"));
client.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Message received: " + msg + " from " +
client.getInfo("username"));
this.sendToAllClients((client.getInfo("username") + " > " + message));
}
}
}



/*if you want to read the information saved in the client
we do client.getId(key) for return the login id*/



protected void kickAllClients(){
Thread [] clientThreadList = getClientConnections();
for(int i=0; i<clientThreadList.length; i++){
try{
((ConnectionToClient)clientThreadList[i]).close();
}
catch (Exception ex){
System.err.println("Error when disconnecting clients");
}
}
}


protected boolean isClosed(){
if(getNumberOfClients()==0 && !isListening()){
return true;
}
return false;
}

//message from server user
public void handleMessageFromServer(Object msg) {
System.out.println("SERVER MSG: " + msg);
this.sendToAllClients(msg);
}


/**
* This method overrides the one in the superclass. Called
* when the server starts listening for connections.
Expand All @@ -62,6 +148,79 @@ protected void serverStarted()
("Server listening for connections on port " + getPort());
}


//I add
protected void clientConnected(ConnectionToClient client) {
System.out.println("Client connected: "+client.toString());
}

synchronized protected void clientDisconnected(ConnectionToClient client) {
System.out.println("Client disconnected: "+client.toString());
}

synchronized protected void clientException(ConnectionToClient client, Throwable exception) {
System.out.println("Client error: "+client.toString()+"exception"+exception.toString());
}

//we create a method that implements the different commands for the server
public void handleMessageFromServerConsole(String message) {
if (message.startsWith("#")) {
String[] parameters = message.split(" ");
String command = parameters[0];
switch (command) {
case "#quit":
//closes the server and then exits it
try {
this.close();
} catch (IOException e) {
System.exit(1);
}
System.exit(0);
break;
case "#stop":
this.stopListening();
break;
case "#close":
try {
this.close();
} catch (IOException e) {
//error closing
}
break;
case "#setport":
if (!this.isListening() && this.getNumberOfClients() < 1) {
super.setPort(Integer.parseInt(parameters[1]));
System.out.println("Port set to " +
Integer.parseInt(parameters[1]));
} else {
System.out.println("Can't do that now. Server is connected.");
}
break;
case "#start":
if (!this.isListening()) {
try {
this.listen();
} catch (IOException e) {
//error listening for clients
}
} else {
System.out.println("We are already started and listening for clients!.");
}
break;
case "#getport":
System.out.println("Current port is " + this.getPort());
break;
default:
System.out.println("Invalid command: '" + command+ "'");
break;
}
} else {
this.sendToAllClients(message);
}
}



/**
* This method overrides the one in the superclass. Called
* when the server stops listening for connections.
Expand All @@ -74,36 +233,5 @@ protected void serverStopped()

//Class methods ***************************************************

/**
* This method is responsible for the creation of
* the server instance (there is no UI in this phase).
*
* @param args[0] The port number to listen on. Defaults to 5555
* if no argument is entered.
*/
public static void main(String[] args)
{
int port = 0; //Port to listen on

try
{
port = Integer.parseInt(args[0]); //Get port from command line
}
catch(Throwable t)
{
port = DEFAULT_PORT; //Set port to 5555
}

EchoServer sv = new EchoServer(port);

try
{
sv.listen(); //Start listening for connections
}
catch (Exception ex)
{
System.out.println("ERROR - Could not listen for clients!");
}
}
}
//End of EchoServer class
Loading