diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..26d33521af10bcc7fd8cea344038eaaeb78d0ef5 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000000000000000000000000000000000000..af8db0bc8576c9cd2efbc47bce61b140810049a7 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="GradleMigrationSettings" migrationVersion="1" /> + <component name="GradleSettings"> + <option name="linkedExternalProjectsSettings"> + <GradleProjectSettings> + <option name="distributionType" value="DEFAULT_WRAPPED" /> + <option name="externalProjectPath" value="$PROJECT_DIR$/src" /> + <option name="gradleHome" value="$PROJECT_DIR$/../../../../../../gradle/gradle-8.0" /> + <option name="gradleJvm" value="18" /> + <option name="modules"> + <set> + <option value="$PROJECT_DIR$/src" /> + </set> + </option> + </GradleProjectSettings> + </option> + </component> +</project> \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000000000000000000000000000000000000..fdc392fe877c32ab51d532fa67f65ff2e75e9061 --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="RemoteRepositoriesConfiguration"> + <remote-repository> + <option name="id" value="central" /> + <option name="name" value="Maven Central repository" /> + <option name="url" value="https://repo1.maven.org/maven2" /> + </remote-repository> + <remote-repository> + <option name="id" value="jboss.community" /> + <option name="name" value="JBoss Community repository" /> + <option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" /> + </remote-repository> + <remote-repository> + <option name="id" value="MavenRepo" /> + <option name="name" value="MavenRepo" /> + <option name="url" value="https://repo.maven.apache.org/maven2/" /> + </remote-repository> + </component> +</project> \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000000000000000000000000000000000000..ade1ecd10ceb8ef28c15c250573346643385cc6d --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="ExternalStorageConfigurationManager" enabled="true" /> + <component name="ProjectRootManager"> + <output url="file://$PROJECT_DIR$/out" /> + </component> +</project> \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000000000000000000000000000000000000..8def1d0f61a85de6714f5e63488a82cf7c637203 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="ProjectModuleManager"> + <modules> + <module fileurl="file://$PROJECT_DIR$/.idea/reseaux_select.iml" filepath="$PROJECT_DIR$/.idea/reseaux_select.iml" /> + </modules> + </component> +</project> \ No newline at end of file diff --git a/.idea/reseaux_select.iml b/.idea/reseaux_select.iml new file mode 100644 index 0000000000000000000000000000000000000000..d6ebd4805981b8400db3e3291c74a743fef9a824 --- /dev/null +++ b/.idea/reseaux_select.iml @@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="UTF-8"?> +<module type="JAVA_MODULE" version="4"> + <component name="NewModuleRootManager" inherit-compiler-output="true"> + <exclude-output /> + <content url="file://$MODULE_DIR$" /> + <orderEntry type="inheritedJdk" /> + <orderEntry type="sourceFolder" forTests="false" /> + </component> +</module> \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000000000000000000000000000000000000..35eb1ddfbbc029bcab630581847471d7f238ec53 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="VcsDirectoryMappings"> + <mapping directory="" vcs="Git" /> + </component> +</project> \ No newline at end of file diff --git a/mesures.csv b/mesures.csv new file mode 100644 index 0000000000000000000000000000000000000000..e2496d38be4d24fe6e5a3c6561ed97fa2d961a72 --- /dev/null +++ b/mesures.csv @@ -0,0 +1,8 @@ +Nombre_de_clients;Temps_moyen_ns;Min_Temps_ns;Max_Temps_ns;Ecart_Type_ns +1;30307300;30307300;30307300;0.0 +2;1401350;1325500;1477200;75850.0 +10;2543170;1373500;3592300;731917.0131237557 +100;10871037;1274900;20403400;5914776.77157806 +1000;5834602;1502200;42603600;2.111329554489539E7 +5000;3072008;922400;61310800;1.8383644560914222E7 +50000;3682380;462800;142229600;2.6974526829630088E7 diff --git a/mesures_latence.csv b/mesures_latence.csv new file mode 100644 index 0000000000000000000000000000000000000000..4b5905ebd28e29d801cf4b9e0b0d1074b2061c74 --- /dev/null +++ b/mesures_latence.csv @@ -0,0 +1,15 @@ +Nombre_de_clients;Temps_moyen_ns;Min_Temps_ns;Max_Temps_ns;Ecart_Type_ns +1;30529600;30529600;30529600;0.0 +2;1040150;928100;1152200;112050.0 +10;2699440;1299400;4103500;928589.5004790869 +100;13855409;1352500;25882300;6976373.27770769 +1000;8356150;1198400;128064800;2.996718981788606E7 +5000;7360120;525100;307029900;7.823948724830812E7 +50000;4634118;436500;306068000;3.703753723305639E7 +1;30111900;30111900;30111900;0.0 +2;1189550;1066700;1312400;122850.0 +10;2521170;1196100;3792200;871711.3020375496 +100;12193571;1271800;21247200;6169356.7433728855 +1000;8795728;1140800;117457600;4.482277478589943E7 +5000;4288497;719400;81092900;3.360717128906339E7 +50000;4160538;428900;253224200;3.6309229373730935E7 diff --git a/src/.gradle/7.5.1/checksums/checksums.lock b/src/.gradle/7.5.1/checksums/checksums.lock new file mode 100644 index 0000000000000000000000000000000000000000..55bcaa48ff0cb762db01892b7a39c2dc7af64b16 Binary files /dev/null and b/src/.gradle/7.5.1/checksums/checksums.lock differ diff --git a/src/.gradle/7.5.1/dependencies-accessors/dependencies-accessors.lock b/src/.gradle/7.5.1/dependencies-accessors/dependencies-accessors.lock new file mode 100644 index 0000000000000000000000000000000000000000..b73662c4ed62341f8eeff33f41db27f3be797a4d Binary files /dev/null and b/src/.gradle/7.5.1/dependencies-accessors/dependencies-accessors.lock differ diff --git a/src/.gradle/7.5.1/dependencies-accessors/gc.properties b/src/.gradle/7.5.1/dependencies-accessors/gc.properties new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/.gradle/7.5.1/executionHistory/executionHistory.bin b/src/.gradle/7.5.1/executionHistory/executionHistory.bin new file mode 100644 index 0000000000000000000000000000000000000000..0904beb5cb2322a96d69b6b217799f0344cefaff Binary files /dev/null and b/src/.gradle/7.5.1/executionHistory/executionHistory.bin differ diff --git a/src/.gradle/7.5.1/executionHistory/executionHistory.lock b/src/.gradle/7.5.1/executionHistory/executionHistory.lock new file mode 100644 index 0000000000000000000000000000000000000000..7acb799609dee6892559eb03e8f652d65b257492 Binary files /dev/null and b/src/.gradle/7.5.1/executionHistory/executionHistory.lock differ diff --git a/src/.gradle/7.5.1/fileChanges/last-build.bin b/src/.gradle/7.5.1/fileChanges/last-build.bin new file mode 100644 index 0000000000000000000000000000000000000000..f76dd238ade08917e6712764a16a22005a50573d Binary files /dev/null and b/src/.gradle/7.5.1/fileChanges/last-build.bin differ diff --git a/src/.gradle/7.5.1/fileHashes/fileHashes.bin b/src/.gradle/7.5.1/fileHashes/fileHashes.bin new file mode 100644 index 0000000000000000000000000000000000000000..fb8f243d87a0bdbc0b99f5996395af53a182b19d Binary files /dev/null and b/src/.gradle/7.5.1/fileHashes/fileHashes.bin differ diff --git a/src/.gradle/7.5.1/fileHashes/fileHashes.lock b/src/.gradle/7.5.1/fileHashes/fileHashes.lock new file mode 100644 index 0000000000000000000000000000000000000000..cb2bf5e224b335c6a71e098fec2227c7a981fa49 Binary files /dev/null and b/src/.gradle/7.5.1/fileHashes/fileHashes.lock differ diff --git a/src/.gradle/7.5.1/fileHashes/resourceHashesCache.bin b/src/.gradle/7.5.1/fileHashes/resourceHashesCache.bin new file mode 100644 index 0000000000000000000000000000000000000000..e34e28faf138c5f1364374a484d387786aa9baca Binary files /dev/null and b/src/.gradle/7.5.1/fileHashes/resourceHashesCache.bin differ diff --git a/src/.gradle/7.5.1/gc.properties b/src/.gradle/7.5.1/gc.properties new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/src/.gradle/buildOutputCleanup/buildOutputCleanup.lock new file mode 100644 index 0000000000000000000000000000000000000000..4dff135a3f27ce7ade9b079de84096b8d5f575d0 Binary files /dev/null and b/src/.gradle/buildOutputCleanup/buildOutputCleanup.lock differ diff --git a/src/.gradle/buildOutputCleanup/cache.properties b/src/.gradle/buildOutputCleanup/cache.properties new file mode 100644 index 0000000000000000000000000000000000000000..3f371e210ccda1780f25646d5cc1f139702cec4b --- /dev/null +++ b/src/.gradle/buildOutputCleanup/cache.properties @@ -0,0 +1,2 @@ +#Thu Mar 13 13:52:33 CET 2025 +gradle.version=7.5.1 diff --git a/src/.gradle/buildOutputCleanup/outputFiles.bin b/src/.gradle/buildOutputCleanup/outputFiles.bin new file mode 100644 index 0000000000000000000000000000000000000000..178cf6fa340ea6028998b743f748e0d069c058ae Binary files /dev/null and b/src/.gradle/buildOutputCleanup/outputFiles.bin differ diff --git a/src/.gradle/file-system.probe b/src/.gradle/file-system.probe new file mode 100644 index 0000000000000000000000000000000000000000..b6b652ca263cb99b402843235f968d7f670682d1 Binary files /dev/null and b/src/.gradle/file-system.probe differ diff --git a/src/.gradle/vcs-1/gc.properties b/src/.gradle/vcs-1/gc.properties new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/build.gradle b/src/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..3cae2d720fb5d1f4383313e27f1395b2b3a30385 --- /dev/null +++ b/src/build.gradle @@ -0,0 +1,19 @@ +plugins { + id 'java' +} + +group 'org.example' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/src/build/classes/java/main/Client.class b/src/build/classes/java/main/Client.class new file mode 100644 index 0000000000000000000000000000000000000000..bf7bf00e0ef39728bbc74f6b380ebd8d3c8c0ebc Binary files /dev/null and b/src/build/classes/java/main/Client.class differ diff --git a/src/build/classes/java/main/ClientNIO.class b/src/build/classes/java/main/ClientNIO.class new file mode 100644 index 0000000000000000000000000000000000000000..ad3ff59556342f395d26652175b1dc07bd6ba9f6 Binary files /dev/null and b/src/build/classes/java/main/ClientNIO.class differ diff --git a/src/build/classes/java/main/Code.class b/src/build/classes/java/main/Code.class new file mode 100644 index 0000000000000000000000000000000000000000..8a5a48672accbe7bf558c2b1e63294588884a9ba Binary files /dev/null and b/src/build/classes/java/main/Code.class differ diff --git a/src/build/classes/java/main/IdleClient.class b/src/build/classes/java/main/IdleClient.class new file mode 100644 index 0000000000000000000000000000000000000000..58ba71257b2a03e7b92e4669e19c0d71c63bd0d8 Binary files /dev/null and b/src/build/classes/java/main/IdleClient.class differ diff --git a/src/build/classes/java/main/ManualMastermindClient.class b/src/build/classes/java/main/ManualMastermindClient.class new file mode 100644 index 0000000000000000000000000000000000000000..f07663a2511b88a9f74345107a5906350a5104b2 Binary files /dev/null and b/src/build/classes/java/main/ManualMastermindClient.class differ diff --git a/src/build/classes/java/main/MastermindBotClient.class b/src/build/classes/java/main/MastermindBotClient.class new file mode 100644 index 0000000000000000000000000000000000000000..487e2d34227b8e6bfff5720ee31494a24bb18c90 Binary files /dev/null and b/src/build/classes/java/main/MastermindBotClient.class differ diff --git a/src/build/classes/java/main/MastermindServer$GameSession.class b/src/build/classes/java/main/MastermindServer$GameSession.class new file mode 100644 index 0000000000000000000000000000000000000000..9228280d73890e34498c7428bc647bdf624953f3 Binary files /dev/null and b/src/build/classes/java/main/MastermindServer$GameSession.class differ diff --git a/src/build/classes/java/main/MastermindServer.class b/src/build/classes/java/main/MastermindServer.class new file mode 100644 index 0000000000000000000000000000000000000000..47524fba4d211283cca898844e0d16ba29e043bb Binary files /dev/null and b/src/build/classes/java/main/MastermindServer.class differ diff --git a/src/build/classes/java/main/ServerNIO$ClientData.class b/src/build/classes/java/main/ServerNIO$ClientData.class new file mode 100644 index 0000000000000000000000000000000000000000..0429fc9a1dc90a5f8f51aea90c77f64fe92761f2 Binary files /dev/null and b/src/build/classes/java/main/ServerNIO$ClientData.class differ diff --git a/src/build/classes/java/main/ServerNIO$GameSession.class b/src/build/classes/java/main/ServerNIO$GameSession.class new file mode 100644 index 0000000000000000000000000000000000000000..23622430f5d5dda10ebc858c7943fb3c0063258a Binary files /dev/null and b/src/build/classes/java/main/ServerNIO$GameSession.class differ diff --git a/src/build/classes/java/main/ServerNIO$PlayerScore.class b/src/build/classes/java/main/ServerNIO$PlayerScore.class new file mode 100644 index 0000000000000000000000000000000000000000..147ad4f12fc86bd0704e97190139e04934c6556c Binary files /dev/null and b/src/build/classes/java/main/ServerNIO$PlayerScore.class differ diff --git a/src/build/classes/java/main/ServerNIO.class b/src/build/classes/java/main/ServerNIO.class new file mode 100644 index 0000000000000000000000000000000000000000..f460e76948e12d5db743e108c4316c6628bd058b Binary files /dev/null and b/src/build/classes/java/main/ServerNIO.class differ diff --git a/src/build/classes/java/main/Stress1.class b/src/build/classes/java/main/Stress1.class new file mode 100644 index 0000000000000000000000000000000000000000..4e0e6c1c098566f8928588db23f93821e10ef3a2 Binary files /dev/null and b/src/build/classes/java/main/Stress1.class differ diff --git a/src/build/tmp/compileJava/previous-compilation-data.bin b/src/build/tmp/compileJava/previous-compilation-data.bin new file mode 100644 index 0000000000000000000000000000000000000000..c6b6ec41f70c960eb665522e31d0982be19a7210 Binary files /dev/null and b/src/build/tmp/compileJava/previous-compilation-data.bin differ diff --git a/src/gradle/wrapper/gradle-wrapper.jar b/src/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..249e5832f090a2944b7473328c07c9755baa3196 Binary files /dev/null and b/src/gradle/wrapper/gradle-wrapper.jar differ diff --git a/src/gradle/wrapper/gradle-wrapper.properties b/src/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..ae04661ee733431762e7ccf8ab9b7409ed44960c --- /dev/null +++ b/src/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/src/gradlew b/src/gradlew new file mode 100644 index 0000000000000000000000000000000000000000..a69d9cb6c20655813e44515156e7253a2a239138 --- /dev/null +++ b/src/gradlew @@ -0,0 +1,240 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/src/gradlew.bat b/src/gradlew.bat new file mode 100644 index 0000000000000000000000000000000000000000..f127cfd49d4024c3e1e0d08ba56399221b4fb25d --- /dev/null +++ b/src/gradlew.bat @@ -0,0 +1,91 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/settings.gradle b/src/settings.gradle new file mode 100644 index 0000000000000000000000000000000000000000..0b03f4c900b035b647cddac0b3c6966eae14437f --- /dev/null +++ b/src/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'src' + diff --git a/src/src/main/java/Client.java b/src/src/main/java/Client.java new file mode 100644 index 0000000000000000000000000000000000000000..1aed5c565abd7f7f6c9a5d722b369450a3b42e9a --- /dev/null +++ b/src/src/main/java/Client.java @@ -0,0 +1,123 @@ +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.*; +import java.util.Scanner; + +public class Client { + private static final String SERVER_ADDRESS = "localhost"; + private static final int PORT = 12345; + private static final int BUFFER_SIZE = 256; + private static Scanner scanner = new Scanner(System.in); + + public static void main(String[] args) { + try { + // Connexion et ouverture du canal + SocketChannel clientChannel = SocketChannel.open(new InetSocketAddress(SERVER_ADDRESS, PORT)); + clientChannel.configureBlocking(false); + Selector selector = Selector.open(); + clientChannel.register(selector, SelectionKey.OP_READ); + + System.out.println("[CLIENT] Connecté au serveur sur " + SERVER_ADDRESS + ":" + PORT); + + // Attente de la demande du serveur + while (true) { + int readyChannels = selector.select(100); // Timeout pour éviter un blocage + if (readyChannels == 0) continue; + + for (SelectionKey key : selector.selectedKeys()) { + selector.selectedKeys().remove(key); + + if (key.isReadable()) { + + ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); + SocketChannel channel = (SocketChannel) key.channel(); + int bytesRead = channel.read(buffer); + + if (bytesRead == -1) { + System.out.println("[CLIENT] Serveur déconnecté"); + channel.close(); + return; + } + + buffer.flip(); + String message = new String(buffer.array(), 0, bytesRead).trim(); + System.out.println("[CLIENT] " + message); + + if (message.contains("Entrez une combinaison")) { + System.out.print("Entrez une combinaison (4 lettres parmi B,G,O,R,W,Y) : "); + String input = scanner.nextLine().toUpperCase(); + + if (!input.matches("[BGORWY]{4}")) { + System.out.println("Combinaison invalide."); + continue; + } + + // Envoie la combinaison au serveur + ByteBuffer sendBuffer = ByteBuffer.wrap(input.getBytes()); + channel.write(sendBuffer); + } else if (message.contains("Entrez votre nom")) { + // Demander à l'utilisateur son nom + System.out.print("Entrez votre nom : "); + String playerName = scanner.nextLine(); + + // Envoyer le nom au serveur + ByteBuffer sendBuffer = ByteBuffer.wrap(playerName.getBytes()); + channel.write(sendBuffer); + + // Attendre une confirmation de la part du serveur + ByteBuffer confirmationBuffer = ByteBuffer.allocate(BUFFER_SIZE); + int confirmationBytesRead = channel.read(confirmationBuffer); + + if (confirmationBytesRead == -1) { + System.out.println("[CLIENT] Serveur déconnecté"); + channel.close(); + return; + } + + confirmationBuffer.flip(); + String confirmationMessage = new String(confirmationBuffer.array(), 0, confirmationBytesRead).trim(); + System.out.println("[CLIENT] " + confirmationMessage); + + // Afficher un message confirmant la victoire et la saisie du nom + System.out.println("[CLIENT] Vous avez gagné !"); + + // Demander les meilleurs scores + System.out.println("Tapez '/SCORE' pour voir les meilleurs scores."); + String command = scanner.nextLine(); + if ("/SCORE".equals(command)) { + ByteBuffer scoreRequestBuffer = ByteBuffer.wrap(command.getBytes()); + channel.write(scoreRequestBuffer); + + // Lire la réponse avec les scores + ByteBuffer scoreBuffer = ByteBuffer.allocate(BUFFER_SIZE); + int scoreBytesRead = channel.read(scoreBuffer); + + if (scoreBytesRead == -1) { + System.out.println("[CLIENT] Serveur déconnecté"); + channel.close(); + return; + } + + scoreBuffer.flip(); + String scoreList = new String(scoreBuffer.array(), 0, scoreBytesRead).trim(); + System.out.println("[CLIENT] Liste des meilleurs scores :"); + System.out.println(scoreList); + } + channel.close(); + return; + } + + else if (message.contains("Félicitations")) { + System.out.println("[CLIENT] Vous avez gagné !"); + return; + } + } + } + } + } catch (IOException e) { + System.err.println("[CLIENT] Erreur de connexion : " + e.getMessage()); + } + } + +} \ No newline at end of file diff --git a/src/src/main/java/ClientNIO.java b/src/src/main/java/ClientNIO.java new file mode 100644 index 0000000000000000000000000000000000000000..2784dfc803e48c7a39ae8bc6915265079547dafd --- /dev/null +++ b/src/src/main/java/ClientNIO.java @@ -0,0 +1,127 @@ +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.*; +import java.util.Scanner; + +public class ClientNIO { + private static final String SERVER_ADDRESS = "localhost"; + private static final int PORT = 12345; + private static final int BUFFER_SIZE = 256; + private static Scanner scanner = new Scanner(System.in); + + public static void main(String[] args) { + try { + // Connexion et ouverture du canal + SocketChannel clientChannel = SocketChannel.open(new InetSocketAddress(SERVER_ADDRESS, PORT)); + clientChannel.configureBlocking(false); + Selector selector = Selector.open(); + clientChannel.register(selector, SelectionKey.OP_READ); + + System.out.println("[CLIENT] Connecté au serveur sur " + SERVER_ADDRESS + ":" + PORT); + + // Attente de la demande du serveur + while (true) { + int readyChannels = selector.select(100); // Timeout pour éviter un blocage + if (readyChannels == 0) continue; + + for (SelectionKey key : selector.selectedKeys()) { + selector.selectedKeys().remove(key); + + if (key.isReadable()) { + + ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); + SocketChannel channel = (SocketChannel) key.channel(); + int bytesRead = channel.read(buffer); + + if (bytesRead == -1) { + System.out.println("[CLIENT] Serveur déconnecté"); + channel.close(); + return; + } + + buffer.flip(); + String message = new String(buffer.array(), 0, bytesRead).trim(); + System.out.println("[CLIENT] " + message); + + if (message.contains("Entrez une combinaison")) { + System.out.print("Entrez une combinaison (4 lettres parmi B,G,O,R,W,Y) : "); + String input = scanner.nextLine().toUpperCase(); + + if (!input.matches("[BGORWY]{4}")) { + System.out.println("Combinaison invalide."); + continue; + } + + // Envoie la combinaison au serveur + ByteBuffer sendBuffer = ByteBuffer.wrap(input.getBytes()); + channel.write(sendBuffer); + } else if (message.contains("Entrez votre nom")) { + // Demander à l'utilisateur son nom + System.out.print("Entrez votre nom : "); + String playerName = scanner.nextLine(); + + // Envoyer le nom au serveur + ByteBuffer sendBuffer = ByteBuffer.wrap(playerName.getBytes()); + channel.write(sendBuffer); + + // Attendre une confirmation de la part du serveur + ByteBuffer confirmationBuffer = ByteBuffer.allocate(BUFFER_SIZE); + int confirmationBytesRead = channel.read(confirmationBuffer); + + if (confirmationBytesRead == -1) { + System.out.println("[CLIENT] Serveur déconnecté"); + channel.close(); + return; + } + + confirmationBuffer.flip(); + String confirmationMessage = new String(confirmationBuffer.array(), 0, confirmationBytesRead).trim(); + System.out.println("[CLIENT] " + confirmationMessage); + + // Afficher un message confirmant la victoire et la saisie du nom + System.out.println("[CLIENT] Vous avez gagné !"); + + // Demander les meilleurs scores + System.out.println("Tapez '/SCORE' pour voir les meilleurs scores."); + String command = scanner.nextLine(); + if ("/SCORE".equals(command)) { + ByteBuffer scoreRequestBuffer = ByteBuffer.wrap(command.getBytes()); + channel.write(scoreRequestBuffer); + + // Lire la réponse avec les scores + ByteBuffer scoreBuffer = ByteBuffer.allocate(BUFFER_SIZE); + int scoreBytesRead = channel.read(scoreBuffer); + + if (scoreBytesRead == -1) { + System.out.println("[CLIENT] Serveur déconnecté"); + channel.close(); + return; + } + + scoreBuffer.flip(); + String scoreList = new String(scoreBuffer.array(), 0, scoreBytesRead).trim(); + System.out.println("[CLIENT] Liste des meilleurs scores :"); + System.out.println(scoreList); + } + + return; + } + else if (message.contains("Meilleurs scores")) { + System.out.println("[CLIENT] " + message); + } + + + else if (message.contains("Félicitations")) { + System.out.println("[CLIENT] Vous avez gagné !"); + return; + } + } + } + } + } catch (IOException e) { + System.err.println("[CLIENT] Erreur de connexion : " + e.getMessage()); + } + } + +} \ No newline at end of file diff --git a/src/src/main/java/Code.java b/src/src/main/java/Code.java new file mode 100644 index 0000000000000000000000000000000000000000..abaf4fb06c956009bec8cfcb73db133def4eb025 --- /dev/null +++ b/src/src/main/java/Code.java @@ -0,0 +1,80 @@ +import java.util.Random; + +public class Code { + public static final int CODE_LENGTH = 4; + public static char[] COLORS = new char[]{'B','G','O','R','W','Y'}; + private final char[] codeWord = new char[CODE_LENGTH]; + + public Code(Random random){ + for (int i = 0; i < CODE_LENGTH; i++) { + codeWord[i] = COLORS[random.nextInt(COLORS.length)]; + } + } + + public Code(String codeString){ + assert(codeString.length() == CODE_LENGTH); + for(int i=0; i<CODE_LENGTH; i++) + codeWord[i] = codeString.charAt(i); + } + + @Override + public String toString() { + return new String(codeWord); + } + + /** + * return the number of colors of guess that are correctly positioned + */ + public int numberOfColorsWithCorrectPosition(Code guess){ + int count = 0; + for(char color : COLORS){ + count += numberOfMatches(color, guess); + } + return count; + } + + /** + * return the number of colors of guess that are in this codeWord + * but do not have the correct position + */ + public int numberOfColorsWithIncorrectPosition(Code guess){ + int count = 0; + for(char color:COLORS){ + int nMatchedOccurrences = numberOfMatches(color, guess); + int nUnmatchedOccurrencesCode = numberOfOccurrences(color, this) - nMatchedOccurrences; + int nUnmatchedOccurrencesGuess = numberOfOccurrences(color, guess) - nMatchedOccurrences; + count += Math.min(nUnmatchedOccurrencesCode, nUnmatchedOccurrencesGuess); + } + return count; + } + + + private int numberOfOccurrences(char color, Code code){ + int count = 0; + for (int i = 0; i < CODE_LENGTH; i++) { + if (code.codeWord[i] == color) count++; + } + return count; + } + + private int numberOfMatches(char color, Code guess){ + int count = 0; + for (int i = 0; i < CODE_LENGTH; i++) { + if ((this.codeWord[i] == guess.codeWord[i]) && (this.codeWord[i] == color)){ + count++; + } + } + return count; + } + + public char[] getCodeWord() { + return codeWord; + } + + @Override + public boolean equals(Object o){ + if (o == null) return false; + if (!(o instanceof Code)) return false; + return this.toString().equals(o.toString()); + } +} diff --git a/src/src/main/java/IdleClient.java b/src/src/main/java/IdleClient.java new file mode 100644 index 0000000000000000000000000000000000000000..c1c5e5e932e6d7ec7384af7164416b6004d6a390 --- /dev/null +++ b/src/src/main/java/IdleClient.java @@ -0,0 +1,31 @@ +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; + +public class IdleClient { + private static final String SERVER_ADDRESS = "localhost"; + private static final int SERVER_PORT = 12345; + + public static void main(String[] args) { + try (SocketChannel clientChannel = SocketChannel.open()) { + clientChannel.connect(new InetSocketAddress(SERVER_ADDRESS, SERVER_PORT)); + sendMessage(clientChannel, "BGOR"); + String response = receiveMessage(clientChannel); + System.out.println("[CLIENT] Réponse du serveur : " + response); + } catch (IOException e) { + System.err.println("[CLIENT] Erreur : " + e.getMessage()); + } + } + + private static void sendMessage(SocketChannel channel, String message) throws IOException { + ByteBuffer buffer = ByteBuffer.wrap(message.getBytes()); + channel.write(buffer); + } + + private static String receiveMessage(SocketChannel channel) throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(256); + channel.read(buffer); + return new String(buffer.array()).trim(); + } +} diff --git a/src/src/main/java/ManualMastermindClient.java b/src/src/main/java/ManualMastermindClient.java new file mode 100644 index 0000000000000000000000000000000000000000..3cafac6a97e38fc8163a7c065e35d0a4aedf7b45 --- /dev/null +++ b/src/src/main/java/ManualMastermindClient.java @@ -0,0 +1,50 @@ +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.util.Scanner; + +public class ManualMastermindClient { + private static final String SERVER_HOST = "localhost"; + private static final int SERVER_PORT = 1234; + + public static void main(String[] args) { + try (SocketChannel socketChannel = SocketChannel.open()) { + socketChannel.connect(new InetSocketAddress(SERVER_HOST, SERVER_PORT)); + Scanner inputScanner = new Scanner(System.in); + + while (true) { + System.out.print("Enter a combination (or /SCORE to see the high scores): "); + String userGuess = inputScanner.nextLine(); + sendToServer(socketChannel, userGuess); + + String serverResponse = receiveFromServer(socketChannel); + System.out.println("[SERVER] " + serverResponse); + + if (serverResponse.contains(" Félicitations")) { + System.out.print("Enter your name to save the score: "); + String playerName = inputScanner.nextLine(); + sendToServer(socketChannel, playerName); + System.out.println("Score saved!"); + break; + } + } + } catch (IOException e) { + System.err.println("[CLIENT] Error: " + e.getMessage()); + } + } + + private static void sendToServer(SocketChannel channel, String message) throws IOException { + ByteBuffer buffer = ByteBuffer.wrap(message.getBytes()); + channel.write(buffer); + } + + private static String receiveFromServer(SocketChannel channel) throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(256); + int bytesRead = channel.read(buffer); + if (bytesRead == -1) { + return ""; // Return empty string if the connection is closed + } + return new String(buffer.array(), 0, bytesRead).trim(); + } +} diff --git a/src/src/main/java/MastermindBotClient.java b/src/src/main/java/MastermindBotClient.java new file mode 100644 index 0000000000000000000000000000000000000000..c96673ea42d69f7548961cd80f81639b105ca08c --- /dev/null +++ b/src/src/main/java/MastermindBotClient.java @@ -0,0 +1,60 @@ +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.util.Random; + +public class MastermindBotClient { + private static final String SERVER_HOST = "localhost"; + private static final int SERVER_PORT = 1234; + private static final String COLOR_OPTIONS = "GBORY"; + + public static void main(String[] args) { + try (SocketChannel socketChannel = SocketChannel.open()) { + socketChannel.connect(new InetSocketAddress(SERVER_HOST, SERVER_PORT)); + Random rand = new Random(); + int attemptCount = 0; + + while (true) { + String generatedGuess = createRandomGuess(rand); + sendToServer(socketChannel, generatedGuess); + System.out.println("[BOT] Sending: " + generatedGuess); + + String serverResponse = receiveFromServer(socketChannel); + System.out.println("[SERVER] " + serverResponse); + + attemptCount++; + + if (serverResponse.contains(" Félicitations")) { + sendToServer(socketChannel, "Bot_" + attemptCount); + System.out.println("[BOT] Score saved!"); + break; + } + } + } catch (IOException e) { + System.err.println("[BOT] Error: " + e.getMessage()); + } + } + + private static String createRandomGuess(Random rand) { + StringBuilder guess = new StringBuilder(); + for (int i = 0; i < 4; i++) { + guess.append(COLOR_OPTIONS.charAt(rand.nextInt(COLOR_OPTIONS.length()))); + } + return guess.toString(); + } + + private static void sendToServer(SocketChannel channel, String message) throws IOException { + ByteBuffer buffer = ByteBuffer.wrap(message.getBytes()); + channel.write(buffer); + } + + private static String receiveFromServer(SocketChannel channel) throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(256); + int bytesRead = channel.read(buffer); + if (bytesRead == -1) { + return ""; // Return empty string if the connection is closed. + } + return new String(buffer.array(), 0, bytesRead).trim(); + } +} diff --git a/src/src/main/java/MastermindServer.java b/src/src/main/java/MastermindServer.java new file mode 100644 index 0000000000000000000000000000000000000000..20c110047a3347a28eae290e5a76c119cb1b93e2 --- /dev/null +++ b/src/src/main/java/MastermindServer.java @@ -0,0 +1,178 @@ +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.*; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public class MastermindServer { + private static final int PORT = 1234; + private static final int BUFFER_SIZE = 256; + private static final Map<String, Integer> scoreBoard = new ConcurrentHashMap<>(); + private static Selector selector; + + public static void main(String[] args) { + try { + selector = Selector.open(); + ServerSocketChannel serverChannel = ServerSocketChannel.open(); + serverChannel.bind(new InetSocketAddress(PORT)); + serverChannel.configureBlocking(false); + serverChannel.register(selector, SelectionKey.OP_ACCEPT); + + System.out.println("[SERVER] Waiting for connections on port " + PORT + "..."); + + while (true) { + selector.select(); + Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator(); + + while (selectedKeys.hasNext()) { + SelectionKey key = selectedKeys.next(); + selectedKeys.remove(); + if (!key.isValid()) continue; + + try { + if (key.isAcceptable()) { + acceptNewClient(serverChannel); + } else if (key.isReadable()) { + handleClientRequest(key); + } + } catch (IOException e) { + key.cancel(); + } + } + } + } catch (IOException e) { + System.err.println("[SERVER] Critical error: " + e.getMessage()); + } + } + + private static void acceptNewClient(ServerSocketChannel serverChannel) throws IOException { + SocketChannel clientChannel = serverChannel.accept(); + clientChannel.configureBlocking(false); + SelectionKey key = clientChannel.register(selector, SelectionKey.OP_READ); + key.attach(new GameSession()); + System.out.println("[SERVER] New client connected: " + clientChannel.getRemoteAddress()); + } + + private static void handleClientRequest(SelectionKey key) { + SocketChannel clientChannel = (SocketChannel) key.channel(); + ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); + + try { + int bytesRead = clientChannel.read(buffer); + if (bytesRead == -1) { + disconnectClient(clientChannel); + return; + } + + buffer.flip(); + String input = new String(buffer.array(), 0, bytesRead).trim(); + System.out.println("[SERVER] Received: " + input); + + GameSession session = (GameSession) key.attachment(); + if (input.equals("/SCORE")) { + sendToClient(clientChannel, getFormattedScoreBoard()); + return; + } + + String response = session.processGuess(input); + sendToClient(clientChannel, response); + + if (response.contains("Congratulations")) { + sendToClient(clientChannel, "Enter your name to save the score:"); + buffer.clear(); + bytesRead = clientChannel.read(buffer); + if (bytesRead > 0) { + buffer.flip(); + String playerName = new String(buffer.array(), 0, bytesRead).trim(); + if (!playerName.isEmpty()) { + scoreBoard.put(playerName, session.getAttempts()); + } + } + } + } catch (IOException e) { + disconnectClient(clientChannel); + } + } + + private static void sendToClient(SocketChannel clientChannel, String message) { + try { + ByteBuffer buffer = ByteBuffer.wrap((message + "\n").getBytes()); + clientChannel.write(buffer); + } catch (IOException e) { + disconnectClient(clientChannel); + } + } + + private static void disconnectClient(SocketChannel clientChannel) { + try { + System.out.println("[SERVER] Client disconnected: " + clientChannel.getRemoteAddress()); + clientChannel.close(); + } catch (IOException e) { + System.err.println("[SERVER] Disconnection error: " + e.getMessage()); + } + } + + private static String getFormattedScoreBoard() { + StringBuilder sb = new StringBuilder("Best Scores:\n"); + scoreBoard.entrySet().stream() + .sorted(Map.Entry.comparingByValue()) + .forEach(entry -> sb.append(entry.getKey()).append(" : ").append(entry.getValue()).append(" attempts\n")); + return sb.toString(); + } + + private static class GameSession { + private final String secretCode; + private int attempts; + + public GameSession() { + this.secretCode = generateSecretCode(); + this.attempts = 0; + System.out.println("[SERVER] Secret code generated: " + secretCode); + } + + public String processGuess(String guess) { + attempts++; + int correctPosition = 0; + int correctColor = 0; + + Map<Character, Integer> secretMap = new HashMap<>(); + for (char c : secretCode.toCharArray()) secretMap.put(c, secretMap.getOrDefault(c, 0) + 1); + + for (int i = 0; i < guess.length(); i++) { + char g = guess.charAt(i); + if (g == secretCode.charAt(i)) { + correctPosition++; + secretMap.put(g, secretMap.get(g) - 1); + } + } + + for (int i = 0; i < guess.length(); i++) { + char g = guess.charAt(i); + if (g != secretCode.charAt(i) && secretMap.getOrDefault(g, 0) > 0) { + correctColor++; + secretMap.put(g, secretMap.get(g) - 1); + } + } + + if (correctPosition == 4) { + return "Congratulations! You've guessed the code in " + attempts + " attempts."; + } + return correctPosition + " correct position(s), " + correctColor + " correct color(s) (Attempt " + attempts + ")"; + } + + public int getAttempts() { + return attempts; + } + + private String generateSecretCode() { + String colors = "BGORWY"; + Random random = new Random(); + StringBuilder code = new StringBuilder(); + for (int i = 0; i < 4; i++) { + code.append(colors.charAt(random.nextInt(colors.length()))); + } + return code.toString(); + } + } +} diff --git a/src/src/main/java/ServerNIO.java b/src/src/main/java/ServerNIO.java new file mode 100644 index 0000000000000000000000000000000000000000..05f2c44c7d72ea7159264a769e391fb626356e55 --- /dev/null +++ b/src/src/main/java/ServerNIO.java @@ -0,0 +1,277 @@ +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.*; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public class ServerNIO { + private static final int PORT = 12345; + private static final int BUFFER_SIZE = 256; + private static final Map<SocketChannel, GameSession> clientSessions = new ConcurrentHashMap<>(); + private static final List<PlayerScore> highScores = new ArrayList<>(); + private static Selector selector; + + public static void main(String[] args) { + try { + selector = Selector.open(); + ServerSocketChannel serverChannel = ServerSocketChannel.open(); + serverChannel.bind(new InetSocketAddress(PORT)); + serverChannel.configureBlocking(false); + serverChannel.register(selector, SelectionKey.OP_ACCEPT); + + System.out.println("[SERVEUR] En attente de connexions sur le port " + PORT + "..."); + + while (true) { + int readyChannels = selector.select(100); // Timeout pour éviter les blocages + + if (readyChannels == 0) continue; + + Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator(); + + while (keyIterator.hasNext()) { + SelectionKey key = keyIterator.next(); + keyIterator.remove(); + + try { + if (key.isAcceptable()) { + acceptClient(serverChannel); + } else if (key.isReadable()) { + readClientData(key); + } + } catch (IOException e) { + key.cancel(); // Retirer la clé en cas d'erreur + } + } + } + } catch (IOException e) { + System.err.println("[SERVEUR] Erreur critique : " + e.getMessage()); + } + } + + private static void acceptClient(ServerSocketChannel serverChannel) throws IOException { + SocketChannel clientChannel = serverChannel.accept(); + clientChannel.configureBlocking(false); + SelectionKey key = clientChannel.register(selector, SelectionKey.OP_READ); + clientSessions.put(clientChannel, new GameSession()); + key.attach(new ClientData()); // Attacher un objet ClientData pour suivre les informations du client + + System.out.println("[SERVEUR] Nouveau client connecté : " + clientChannel.getRemoteAddress()); + + // Envoi du message initial demandant une combinaison + sendMessage(clientChannel, "Entrez une combinaison (4 lettres parmi B,G,O,R,W,Y) : "); + } + + private static void readClientData(SelectionKey key) { + SocketChannel clientChannel = (SocketChannel) key.channel(); + ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); + + try { + int bytesRead = clientChannel.read(buffer); + if (bytesRead == -1) { + disconnectClient(clientChannel); + return; + } + + buffer.flip(); + String input = new String(buffer.array(), 0, bytesRead).trim(); + System.out.println("[SERVEUR] Réception : " + input); + + GameSession session = clientSessions.get(clientChannel); + ClientData clientData = (ClientData) key.attachment(); // Récupérer les données attachées + + if (session != null) { + if (session.isGameFinished()) { + // Si le jeu est terminé, demander le nom du joueur + if (clientData.getPlayerName() == null) { + clientData.setPlayerName(input); // Nom du joueur reçu + int score = clientData.getAttempts(); + PlayerScore playerScore = new PlayerScore(clientData.getPlayerName(), score); + session.setPlayerScore(playerScore); + highScores.add(playerScore); + highScores.sort(Comparator.comparingInt(PlayerScore::getScore)); // Trier par score + + sendMessage(clientChannel, "Votre nom a été enregistré avec un score de " + score + " tentatives.\n"); + sendMessage(clientChannel, "Tapez /SCORE pour voir le tableau des meilleurs scores."); + key.interestOps(SelectionKey.OP_READ); // Revenir en mode lecture pour recevoir /SCORE ou d'autres commandes + } else { + handleClientRequest(clientChannel, input); // Appeler la méthode pour gérer les commandes comme /SCORE + } + } else { + // Si le jeu n'est pas encore terminé, traiter la tentative de combinaison + String response = session.processGuess(input); + clientData.incrementAttempts(); + sendMessage(clientChannel, response); + + if (response.contains("Félicitations")) { + sendMessage(clientChannel, "Félicitations ! Entrez votre nom : "); + key.interestOps(SelectionKey.OP_WRITE); // Passer en mode écriture pour obtenir le nom + } else { + sendMessage(clientChannel, "Entrez une nouvelle combinaison : "); + key.interestOps(SelectionKey.OP_READ); // Revenir en mode lecture pour recevoir la nouvelle tentative + } + } + } + } catch (IOException e) { + disconnectClient(clientChannel); + } + } + + private static void handleClientRequest(SocketChannel clientChannel, String input) { + // Si le client envoie "/SCORE" + if ("/SCORE".equals(input)) { + // Afficher les meilleurs scores + StringBuilder scoreList = new StringBuilder("Meilleurs scores :\n"); + + // Trie les scores par ordre décroissant si ce n'est pas déjà fait + highScores.sort((ps1, ps2) -> Integer.compare(ps2.getScore(), ps1.getScore())); + + // Construire la liste des meilleurs scores + for (PlayerScore ps : highScores) { + scoreList.append(ps).append("\n"); + } + + // Envoyer la liste des meilleurs scores au client + sendMessage(clientChannel, scoreList.toString()); + } + } + + + + private static int countCorrectPositions(String secretCode, String guess) { + int count = 0; + for (int i = 0; i < secretCode.length(); i++) { + if (secretCode.charAt(i) == guess.charAt(i)) { + count++; + } + } + return count; + } + + private static int countIncorrectPositions(String secretCode, String guess) { + int count = 0; + for (int i = 0; i < secretCode.length(); i++) { + if (secretCode.indexOf(guess.charAt(i)) != -1 && secretCode.charAt(i) != guess.charAt(i)) { + count++; + } + } + return count; + } + + + private static void sendMessage(SocketChannel clientChannel, String message) { + try { + ByteBuffer buffer = ByteBuffer.wrap(message.getBytes()); + clientChannel.write(buffer); + } catch (IOException e) { + disconnectClient(clientChannel); + } + } + + private static void disconnectClient(SocketChannel clientChannel) { + try { + System.out.println("[SERVEUR] Client déconnecté : " + clientChannel.getRemoteAddress()); + GameSession session = clientSessions.remove(clientChannel); + if (session != null && session.isGameFinished()) { + PlayerScore score = session.getPlayerScore(); + if (score != null) { // Vérifier si le score est bien défini + highScores.add(score); + highScores.sort(Comparator.comparingInt(PlayerScore::getScore)); // Trier par score + } + } + clientChannel.close(); + } catch (IOException e) { + System.err.println("[SERVEUR] Erreur de fermeture : " + e.getMessage()); + } + } + + + private static class GameSession { + private final String secretCode; + private boolean gameFinished = false; + private PlayerScore playerScore; + + public GameSession() { + this.secretCode = generateSecretCode(); + System.out.println("[SERVEUR] Code secret généré : " + secretCode); + } + + public String processGuess(String guess) { + if (guess.equals(secretCode)) { + gameFinished = true; + return "Félicitations ! Vous avez trouvé la combinaison correcte."; + } + return "Mauvaise combinaison, réessayez."; + } + + private String generateSecretCode() { + String colors = "BGORWY"; + Random random = new Random(); + StringBuilder code = new StringBuilder(); + for (int i = 0; i < 4; i++) { + code.append(colors.charAt(random.nextInt(colors.length()))); + } + return code.toString(); + } + + public boolean isGameFinished() { + return gameFinished; + } + + public PlayerScore getPlayerScore() { + return playerScore; + } + + public void setPlayerScore(PlayerScore playerScore) { + this.playerScore = playerScore; + } + + public String getSecretCode() { + return secretCode; + } + } + + private static class ClientData { + private int attempts = 0; + private String playerName; + + public void incrementAttempts() { + attempts++; + } + + public int getAttempts() { + return attempts; + } + + public void setPlayerName(String name) { + this.playerName = name; + } + + public String getPlayerName() { + return playerName; + } + } + + private static class PlayerScore { + private final String name; + private final int score; + + public PlayerScore(String name, int score) { + this.name = name; + this.score = score; + } + + public String getName() { + return name; + } + + public int getScore() { + return score; + } + + @Override + public String toString() { + return name + ": " + score + " tentatives"; + } + } +} diff --git a/src/src/main/java/Stress1.java b/src/src/main/java/Stress1.java new file mode 100644 index 0000000000000000000000000000000000000000..ba37970c9fc0b90d7e3963382f1f32d567b496d9 --- /dev/null +++ b/src/src/main/java/Stress1.java @@ -0,0 +1,86 @@ +import java.io.*; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicLong; + +public class Stress1 { + private static final String SERVER_ADDRESS = "localhost"; + private static final int SERVER_PORT = 12345; + private static final int MAX_CLIENTS = 1000; + + public static void main(String[] args) { + String filePath = "mesures.csv"; + File file = new File(filePath); + boolean isNewFile = !file.exists(); + + try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) { + if (isNewFile) { + writer.write("Nombre_de_clients;Temps_moyen_ns;Min_Temps_ns;Max_Temps_ns;Ecart_Type_ns\n"); + } + + for (int n : new int[]{1, 2, 10, 100, 1000, 5000, 50000}) { + ExecutorService executor = Executors.newCachedThreadPool(); + CountDownLatch latch = new CountDownLatch(n); + AtomicLong totalResponseTime = new AtomicLong(); + List<Long> responseTimes = new CopyOnWriteArrayList<>(); + + for (int i = 0; i < n; i++) { + executor.submit(() -> { + long startTime = System.nanoTime(); + try (SocketChannel clientChannel = SocketChannel.open()) { + clientChannel.connect(new InetSocketAddress(SERVER_ADDRESS, SERVER_PORT)); + sendMessage(clientChannel, "BGOR"); + String response = receiveMessage(clientChannel); + long responseTime = System.nanoTime() - startTime; + totalResponseTime.addAndGet(responseTime); + responseTimes.add(responseTime); + } catch (IOException e) { + System.err.println("Erreur lors de la connexion client : " + e.getMessage()); + } finally { + latch.countDown(); + } + }); + } + + latch.await(); + executor.shutdown(); + + // Calculs statistiques + long averageResponseTime = totalResponseTime.get() / n; + long minResponseTime = responseTimes.stream().min(Long::compare).orElse(0L); + long maxResponseTime = responseTimes.stream().max(Long::compare).orElse(0L); + + // Calcul de la variance et écart-type + double mean = totalResponseTime.get() / (double) n; + double sumSquaredDifferences = 0.0; + for (long responseTime : responseTimes) { + sumSquaredDifferences += Math.pow(responseTime - mean, 2); + } + double variance = sumSquaredDifferences / n; + double ecartType = Math.sqrt(variance); + + writer.write(n + ";" + averageResponseTime + ";" + minResponseTime + ";" + maxResponseTime + ";" + ecartType + "\n"); + System.out.println("Clients: " + n + " | Moyenne: " + averageResponseTime + " ns | Min: " + minResponseTime + " ns | Max: " + maxResponseTime + " ns | Écart-type: " + ecartType + " ns"); + } + + System.out.println("Tests terminés. Résultats sauvegardés dans " + filePath); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + } + + private static void sendMessage(SocketChannel channel, String message) throws IOException { + ByteBuffer buffer = ByteBuffer.wrap(message.getBytes()); + channel.write(buffer); + } + + private static String receiveMessage(SocketChannel channel) throws IOException { + ByteBuffer buffer = ByteBuffer.allocate(256); + channel.read(buffer); + return new String(buffer.array()).trim(); + } +}