├── src
└── main
│ └── java
│ └── edu
│ └── unict
│ └── tswd
│ ├── socket
│ ├── ProvePassate
│ │ ├── Cubo
│ │ │ ├── Makefile
│ │ │ ├── consegna.md
│ │ │ ├── client.c
│ │ │ └── Server.java
│ │ └── Mul
│ │ │ ├── Makefile
│ │ │ ├── client.c
│ │ │ ├── consegna.md
│ │ │ ├── ServerA.java
│ │ │ ├── ServerB.java
│ │ │ ├── ServerC.java
│ │ │ └── ServerD.java
│ ├── tcp
│ │ ├── echoservermt
│ │ │ ├── Client.java
│ │ │ ├── Server.java
│ │ │ ├── ServerThread.java
│ │ │ └── ClientThread.java
│ │ ├── finger
│ │ │ └── finger.java
│ │ ├── biblioteca
│ │ │ ├── Client.java
│ │ │ └── BibliotecaServer.java
│ │ ├── simplescraper
│ │ │ └── webscraper.java
│ │ └── echoserver
│ │ │ ├── EchoServer.java
│ │ │ └── EchoClient.java
│ ├── nio
│ │ ├── sampleapp
│ │ │ ├── Client.java
│ │ │ └── Server.java
│ │ └── baeldung
│ │ │ ├── EchoClient.java
│ │ │ └── EchoServer.java
│ └── udp
│ │ └── filestreamer
│ │ ├── DatagramUtility.java
│ │ ├── LineUtility.java
│ │ ├── MulticastClient.java
│ │ ├── MulticastServer.java
│ │ ├── LineServer.java
│ │ └── LineClient.java
│ └── thread
│ ├── soccergame
│ ├── Game.class
│ ├── Team.class
│ ├── SoccerGame.class
│ ├── SoccerGame.java
│ ├── Game.java
│ ├── README.md
│ └── Team.java
│ ├── goosegame
│ ├── GooseGame.java
│ ├── Game.java
│ └── Player.java
│ ├── ProvePassate
│ └── ValoreAssoluto
│ │ ├── Main.java
│ │ ├── Shared.java
│ │ ├── consegna.md
│ │ └── MyThread.java
│ ├── pc
│ ├── test.java
│ ├── consumer.java
│ ├── container.java
│ └── producer.java
│ ├── hellothread
│ ├── myRunnable2.java
│ ├── myRunnable.java
│ ├── myThread.java
│ ├── myThread2.java
│ ├── myRunnable3.java
│ ├── hello.java
│ ├── myRunnable4.java
│ ├── myThread4.java
│ ├── myThread3.java
│ ├── hello2.java
│ ├── hello21builder.java
│ ├── hello21buildervirtual.java
│ ├── hello3.java
│ ├── hello21.java
│ └── hello4.java
│ ├── asyncronous_communication
│ ├── Main.java
│ ├── Logger.java
│ ├── Server.java
│ └── Worker.java
│ └── dicegame
│ ├── Game.java
│ ├── JackpotRefiller.java
│ ├── Banco.java
│ └── Player.java
├── resources
├── dante.txt
└── saggezza.txt
├── .gitignore
├── pom.xml
├── Dockerfile
└── README.md
/src/main/java/edu/unict/tswd/socket/ProvePassate/Cubo/Makefile:
--------------------------------------------------------------------------------
1 | CFLAGS=-Wall
2 |
3 | all: client
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/ProvePassate/Mul/Makefile:
--------------------------------------------------------------------------------
1 | CFLAGS=-Wall
2 |
3 | all: client
--------------------------------------------------------------------------------
/resources/dante.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unict-dmi-wsos/tsdw-java-examples/HEAD/resources/dante.txt
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/soccergame/Game.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unict-dmi-wsos/tsdw-java-examples/HEAD/src/main/java/edu/unict/tswd/thread/soccergame/Game.class
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/soccergame/Team.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unict-dmi-wsos/tsdw-java-examples/HEAD/src/main/java/edu/unict/tswd/thread/soccergame/Team.class
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/soccergame/SoccerGame.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unict-dmi-wsos/tsdw-java-examples/HEAD/src/main/java/edu/unict/tswd/thread/soccergame/SoccerGame.class
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | pom.xml.tag
3 | pom.xml.releaseBackup
4 | pom.xml.versionsBackup
5 | pom.xml.next
6 | release.properties
7 | dependency-reduced-pom.xml
8 | buildNumber.properties
9 | .mvn/timing.properties
10 | # https://github.com/takari/maven-wrapper#usage-without-binary-jar
11 | .mvn/wrapper/maven-wrapper.jar
12 |
13 | # Eclipse m2e generated files
14 | # Eclipse Core
15 | .project
16 | # JDT-specific (Eclipse Java Development Tools)
17 | .classpath
18 |
19 | # Editors
20 | .idea
21 | .vscode
22 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/goosegame/GooseGame.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.goosegame;
2 |
3 | public class GooseGame {
4 | public static void main(String[] args) throws InterruptedException {
5 | Game game =new Game();
6 | Player t0=new Player(0,game);
7 | Player t1=new Player(1,game);
8 | t0.start();
9 | t1.start();
10 | t0.join();
11 | t1.join();
12 | System.out.println("****** Game Over ******");
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/ProvePassate/ValoreAssoluto/Main.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.ProvePassate.ValoreAssoluto;
2 |
3 | public class Main {
4 |
5 | public static void main(String[] args) throws Exception {
6 | Shared shared = new Shared();
7 | Thread t1 = new MyThread(shared, 1);
8 | Thread t2 = new MyThread(shared, 2);
9 |
10 | t1.start();
11 | t2.start();
12 |
13 | t1.join();
14 | t2.join();
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/pc/test.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.pc;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/jthread.tar
3 | public class test {
4 | public static void main(String[] args) {
5 | container containerIstance = new container();
6 | producer p1 = new producer(containerIstance);
7 | consumer c1 = new consumer(containerIstance, "c1");
8 | consumer c2 = new consumer(containerIstance, "c2");
9 | c1.start();
10 | c2.start();
11 | p1.start();
12 |
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/myRunnable2.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 |
3 | public class myRunnable2 implements Runnable {
4 | @Override
5 | public void run() {
6 | // Starting
7 | System.out.println("In run di myRunnable");
8 | Thread t = Thread.currentThread();
9 | System.out.println("myRunnable running pid "+t.toString());
10 | System.out.println(t.getName());
11 | for (int i = 0; i < 10; i++) {
12 | System.out.println("\t_");
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/asyncronous_communication/Main.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.asyncronous_communication;
2 |
3 | import sun.misc.Signal;
4 | import sun.misc.SignalHandler;
5 |
6 | public class Main {
7 | public static void main(String[] args) {
8 | Server s = new Server();
9 |
10 | Runtime.getRuntime().addShutdownHook(new Thread() {
11 | public void run() {
12 | System.out.println("Closing all connection after CTRL-C");
13 | s.close_connection();
14 | }
15 | });
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/myRunnable.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 |
3 | import static java.lang.Thread.sleep;
4 |
5 | public class myRunnable implements Runnable {
6 | @Override
7 | public void run() {
8 | // Starting
9 | System.out.println("In run di myRunnable");
10 | Thread t = Thread.currentThread();
11 | System.out.println("myRunnable running pid "+t.toString());
12 | System.out.println(t.getName());
13 | for (int i = 0; i < 10000000; i++) {
14 | System.out.println("\t_");
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | groupId
8 | tswd-java-examples
9 | 1.0-SNAPSHOT
10 |
11 |
12 | 11
13 | 11
14 |
15 |
16 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/goosegame/Game.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.goosegame;
2 |
3 | // Class that manages the game
4 | public class Game {
5 | int round=0;
6 |
7 | public int getRound(){
8 | return(round);
9 | }
10 |
11 | public synchronized void setRound(int k){
12 | round = k;
13 | }
14 |
15 | public synchronized void gameWait() throws InterruptedException {
16 | wait();
17 | }
18 |
19 | public synchronized void gameNotify() throws InterruptedException {
20 | notifyAll();
21 | }
22 |
23 | public void sleep() throws InterruptedException {
24 | Thread.sleep(500);
25 | }
26 | }
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/soccergame/SoccerGame.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.soccergame;
2 |
3 | public class SoccerGame {
4 | public static void main(String[] args) throws InterruptedException {
5 | Game game = new Game();
6 | Team t0=new Team(0,"Italia",game);
7 | Team t1=new Team(1,"Croazia",game);
8 | t0.start();
9 | t1.start();
10 | t0.join();
11 | t1.join();
12 | System.out.println("Final Score");
13 | System.out.println(t0.getTeamName()+" vs "+t1.getTeamName() + " "+t0.getGoal()+ "-" +t1.getGoal());
14 | System.out.println("****** Game Over ******");
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/ProvePassate/ValoreAssoluto/Shared.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.ProvePassate.ValoreAssoluto;
2 |
3 | import java.util.Random;
4 |
5 | public class Shared {
6 | Random rand = new Random();
7 | private int x;
8 |
9 | public Shared(){
10 | this.x = rand.nextInt(11);
11 | }
12 |
13 | public int getX(){
14 | return this.x;
15 | }
16 |
17 | public synchronized void setX(int t){
18 | this.x = t;
19 | }
20 |
21 | public synchronized void sharedWait() throws InterruptedException{
22 | wait();
23 | }
24 |
25 | public synchronized void sharedNotify(){
26 | notifyAll();
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/myThread.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/jthread.tar
3 |
4 | public class myThread extends Thread {
5 | myThread() {
6 | System.out.println("myThread constructor");
7 | }
8 |
9 | public void run() {
10 | // Starting
11 | System.out.println("In run di myThread");
12 | Thread t = Thread.currentThread();
13 | System.out.println("myThread running pid " + t.toString());
14 | System.out.println(t.getName());
15 | for (int i = 0; i < 1000000000; i++) {
16 | System.out.println("\t\t>");
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/myThread2.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/jthread.tar
3 |
4 | public class myThread2 extends Thread {
5 | myThread2() {
6 |
7 | System.out.println("myThread constructor");
8 | }
9 | public void run() {
10 | // Starting
11 | System.out.println("In run di myThread");
12 | Thread t = Thread.currentThread();
13 | System.out.println("myThread running pid "+t.toString());
14 | System.out.println(t.getName());
15 | for (int i = 0; i < 10000000; i++) {
16 | System.out.println("\t\t>");
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/pc/consumer.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.pc;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/jthread.tar
3 | public class consumer extends Thread{
4 | private container cont;
5 | private final int EOF=-1;
6 | private String name;
7 | public consumer (container c, String name) {
8 | cont = c;
9 | this.name = name;
10 | }
11 |
12 | public void run() {
13 | System.out.println(name+" C: inizio");
14 | int num=0;
15 | while (num != EOF) {
16 | num = cont.get();
17 | System.out.println(name+" C: prelevo " + num);
18 | }
19 | System.out.println(name+" C: termino\n");
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/ProvePassate/Cubo/consegna.md:
--------------------------------------------------------------------------------
1 | # Tecniche di Programmazione Concorrente e Distribuita 24/05/2016
2 | ### Socket (C o Java)
3 |
4 | Scrivere un server che si metta in ascolto sul port `3333` in grado di rispondere ad un messaggio composto da una sola stringa
5 | `str` composta da cifre numeriche (da 0 a 9) terminata dal carattere `\n`.
6 |
7 | Il server:
8 | - Converte la stringa ricevuta _str_ in un numero intero _n_.
9 | - Il numero viene usato come input per il metodo `int cubo(int n)` che restituisce il cubo dell’intero _n_.
10 | - Invia al client il valore restituito dal metodo `cubo()`.
11 |
12 | - Testare il server con un semplice client o con telnet.
13 |
14 | - Tempo a disposizione: 35 minuti.
15 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/tcp/echoservermt/Client.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.tcp.echoservermt;
2 |
3 | import java.io.IOException;
4 | import java.net.InetAddress;
5 |
6 | public class Client {
7 | static final int MAX_THREADS = 1;
8 |
9 | public static void main(String[] args) throws IOException,InterruptedException {
10 | InetAddress addr;
11 | if (args.length == 0) addr = InetAddress.getByName(null);
12 | else addr = InetAddress.getByName(args[0]);
13 |
14 | while(true) {
15 | if (ClientThread.threadCount() < MAX_THREADS)
16 | new ClientThread(addr);
17 | Thread.currentThread();
18 | Thread.sleep(1000);
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | # Creating first container to compile Java code and create jar file
2 | FROM maven:3-openjdk-11 AS build
3 | WORKDIR /app
4 |
5 | # Copying pom.xml file to container
6 | COPY pom.xml .
7 |
8 | # Downloading dependencies
9 | RUN mvn -f ./pom.xml clean package
10 |
11 | # Copying source code to container
12 | COPY src src
13 | COPY resources resources
14 |
15 | # Compiling and creating jar file
16 | RUN mvn -f ./pom.xml package
17 |
18 | # Creating second container to run jar file
19 | FROM openjdk:11
20 | ENV BUILD "tswd-java-examples-1.0-SNAPSHOT.jar"
21 | WORKDIR /app
22 |
23 | # Copying jar file from first container to second container
24 | COPY --from=build /app/target/${BUILD} app.jar
25 |
26 | # Running jar file
27 | ENTRYPOINT ["java","-cp","app.jar"]
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/myRunnable3.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 |
3 | import static java.lang.Thread.sleep;
4 |
5 | public class myRunnable3 implements Runnable {
6 | @Override
7 | public void run() {
8 | // Starting
9 | System.out.println("In run di myRunnable");
10 | Thread t = Thread.currentThread();
11 | System.out.println("myRunnable running pid "+t.toString());
12 | System.out.println(t.getName());
13 | for (int i = 0; i < 5000; i++) {
14 | System.out.println("\t_");
15 | try {
16 | sleep(1);
17 | } catch (InterruptedException e) {
18 | e.printStackTrace();
19 | }
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/hello.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/jthread.tar
3 | import java.util.Random;
4 |
5 | public class hello {
6 | public static void main(String[] args) throws InterruptedException {
7 | // Main is a deamon thread
8 | Thread tMain = Thread.currentThread();
9 | System.out.println("Main Thread "+tMain.toString());
10 | // Let's create a new thread with method 1
11 | myThread t = new myThread();
12 | // Start thread
13 | t.start();
14 | // In "parallel" here
15 | for (int i = 0; i < 1000000000; i++) {
16 | System.out.println("<");
17 | }
18 | System.out.println("");
19 | System.out.println("This is the end");
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/myRunnable4.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 |
3 | import java.util.Random;
4 |
5 | import static java.lang.Thread.sleep;
6 |
7 | public class myRunnable4 implements Runnable {
8 | @Override
9 | public void run() {
10 | // Starting
11 | System.out.println("In run di myRunnable");
12 | Thread t = Thread.currentThread();
13 | System.out.println("myRunnable running pid "+t.toString());
14 | System.out.println(t.getName());
15 | for (int i = 0; i < 5000; i++) {
16 | System.out.println("\t_");
17 | try {
18 | sleep(new Random().nextInt(5)); // Poor Ascii ART
19 | } catch (InterruptedException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/soccergame/Game.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.soccergame;
2 |
3 | public class Game {
4 | int round=0; // First team to play
5 | int time=0; // Time in minute of the game
6 |
7 | public int getRound(){
8 | return(round);
9 | }
10 |
11 | public int getTime(){
12 | return(time);
13 | }
14 |
15 | public synchronized void addTime(){
16 | time+=1;
17 | }
18 |
19 | public synchronized void setRound(int k){
20 | round = k;
21 | }
22 |
23 | public synchronized void gameWait() throws InterruptedException {
24 | wait();
25 | }
26 |
27 | public synchronized void gameNotify() throws InterruptedException {
28 | notifyAll();
29 | }
30 |
31 | public void sleep() throws InterruptedException {
32 | Thread.sleep(10);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/myThread4.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/jthread.tar
3 |
4 | import java.util.Random;
5 |
6 | public class myThread4 extends Thread {
7 | myThread4() {
8 | System.out.println("myThread constructor");
9 | }
10 | public void run() {
11 | // Starting
12 | System.out.println("In run di myThread");
13 | Thread t = Thread.currentThread();
14 | System.out.println("myThread running pid "+t.toString());
15 | System.out.println(t.getName());
16 | for (int i = 0; i < 5000; i++) {
17 | try {
18 | System.out.println("\t\t>");
19 | sleep(new Random().nextInt(5)); // Poor Ascii ART
20 | } catch (InterruptedException e) { }
21 |
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/myThread3.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/jthread.tar
3 |
4 | public class myThread3 extends Thread {
5 | myThread3() {
6 | System.out.println("myThread constructor");
7 | }
8 | public void run() {
9 | // Starting
10 | System.out.println("In run di myThread");
11 | Thread t = Thread.currentThread();
12 | System.out.println("myThread running pid "+t.toString());
13 | System.out.println(t.getName());
14 | for (int i = 0; i < 5000; i++) {
15 | System.out.println("\t\t>");
16 | try {
17 | sleep(1);
18 | } catch (InterruptedException e) {
19 | e.printStackTrace();
20 | }
21 | //sleep(new Random().nextInt(5)); // Poor Ascii ART
22 |
23 |
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/hello2.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/jthread.tar
3 | import static java.lang.Thread.sleep;
4 |
5 | public class hello2 {
6 | public static void main(String[] args) throws InterruptedException {
7 | // Main is a deamon
8 | Thread tMain = Thread.currentThread();
9 | System.out.println("Main Thread "+tMain.toString());
10 | myThread2 t = new myThread2();
11 | // Start thread
12 | t.start();
13 | // Create another thread
14 | myRunnable myRunnable = new myRunnable();
15 | Thread myRunnableThread = new Thread(myRunnable);
16 | // Start
17 | myRunnableThread.start();
18 |
19 | // In parallel here
20 | for (int i = 0; i < 10000000; i++) {
21 | System.out.println("<");
22 | }
23 |
24 | System.out.println("");
25 | System.out.println("This is the end");
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/dicegame/Game.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.dicegame;
2 |
3 | public class Game {
4 | public static void main(String[] args) throws InterruptedException {
5 | Banco banco = new Banco(10, 100);
6 | Player p1 = new Player("Paperino", 0, banco);
7 | Player p2 = new Player("Gastone", 100, banco);
8 | Player p3 = new Player("Paperone", 10, banco);
9 | JackpotRefiller refiller = new JackpotRefiller(banco, 100);
10 |
11 | p1.start();
12 | p2.start();
13 |
14 | refiller.start(); // Be careful with start of refiller, since checks number of players
15 | // Thread.sleep(5000); Consider to make other player start later
16 | p3.start();
17 |
18 | p1.join();
19 | p2.join();
20 | p3.join();
21 | refiller.join();
22 | System.out.println("*** Game Over ***");
23 | p1.printStatus();
24 | p2.printStatus();
25 | p3.printStatus();
26 | }
27 | }
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/hello21builder.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 |
3 | public class hello21builder {
4 | public static void main(String[] args) throws InterruptedException {
5 | // Main is a deamon
6 | Thread tMain = Thread.currentThread();
7 | System.out.println("Main Thread "+tMain.toString());
8 | // Java Lambda Expression Example: Thread Example
9 | // See https://www.codejava.net/java-core/the-java-language/java-8-lambda-runnable-example
10 |
11 | Runnable fn = () -> {
12 | for (int i=0; i<10; i++) {
13 | System.out.println("Hello from a thread!");
14 | }
15 | };
16 |
17 | Thread.Builder builder = Thread.ofPlatform().name("worker-", 0);
18 |
19 | for (int j=0;j<10;j++) {
20 | Thread t = builder.start(fn); // name "worker-0"
21 | System.out.println("Name of thread"+t.getName());
22 | }
23 | System.out.println("This is the end");
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/hello21buildervirtual.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 |
3 | public class hello21buildervirtual {
4 | public static void main(String[] args) throws InterruptedException {
5 | // Main is a deamon
6 | Thread tMain = Thread.currentThread();
7 | System.out.println("Main Thread "+tMain.toString());
8 | // Java Lambda Expression Example: Thread Example
9 | // See https://www.codejava.net/java-core/the-java-language/java-8-lambda-runnable-example
10 |
11 | Runnable fn = () -> {
12 | for (int i=0; i<10; i++) {
13 | System.out.println("Hello from a thread!");
14 | }
15 | };
16 |
17 | Thread.Builder builder = Thread.ofVirtual().name("worker-", 0);
18 |
19 | for (int j=0;j<10;j++) {
20 | Thread t = builder.start(fn); // name "worker-0"
21 | System.out.println("Name of thread"+t.getName());
22 | }
23 | System.out.println("This is the end");
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/hello3.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/jthread.tar
3 | import static java.lang.Thread.sleep;
4 |
5 | import java.util.Random;
6 |
7 | public class hello3 {
8 | public static void main(String[] args) throws InterruptedException {
9 | // Main is a deamon
10 | Thread tMain = Thread.currentThread();
11 | System.out.println("Main Thread "+tMain.toString());
12 | myThread3 t = new myThread3();
13 | // Start thread
14 | t.start();
15 | // Create another thread
16 | myRunnable3 myRunnable = new myRunnable3();
17 | Thread myRunnableThread = new Thread(myRunnable);
18 | // Start
19 | myRunnableThread.start();
20 |
21 | // In parallel here
22 | for (int i = 0; i < 5000; i++) {
23 | System.out.print("<");
24 | //sleep(1);
25 | sleep(new Random().nextInt(5)); // Poor Ascii ART
26 | }
27 | System.out.println("This is the end");
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/pc/container.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.pc;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/jthread.tar
3 | public class container {
4 | private int contents;
5 | private boolean available = false;
6 |
7 | public synchronized int get() {
8 | while (available == false) {
9 | try {
10 | // attende che un dato sia disponibile
11 | wait();
12 | } catch (InterruptedException e) { }
13 | }
14 | available = false;
15 | // notifica che un dato e' stato consumato ed
16 | // un produttore puo' inserirne un altro
17 | notifyAll();
18 | return contents;
19 | }
20 |
21 | public synchronized void put(int value) {
22 | while (available == true) {
23 | try {
24 | // attende che un dato sia consumato
25 | wait();
26 | } catch (InterruptedException e) { }
27 | }
28 | contents = value;
29 | available = true;
30 | // notifica che un dato e' stato inserito
31 | notifyAll();
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/ProvePassate/Mul/client.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | int main(void){
8 | struct sockaddr_in remote_addr;
9 | socklen_t len = sizeof(struct sockaddr_in);
10 | char buffer[BUFSIZ];
11 | int sockfd, n;
12 |
13 | if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
14 | perror("socket");
15 | return EXIT_FAILURE;
16 | }
17 |
18 | memset(&remote_addr, 0, len);
19 |
20 | remote_addr.sin_family = AF_INET;
21 | remote_addr.sin_port = htons(7777);
22 | remote_addr.sin_addr.s_addr = inet_addr("0.0.0.0"); //static version
23 |
24 | if((connect(sockfd, (struct sockaddr*)&remote_addr, len)) < 0){
25 | perror("connect");
26 | return EXIT_FAILURE;
27 | }
28 |
29 | sprintf(buffer, "1234\n");
30 |
31 | if((send(sockfd, buffer, strlen(buffer), 0)) < 0){
32 | perror("send");
33 | return EXIT_FAILURE;
34 | }
35 | if((n = recv(sockfd, &buffer, BUFSIZ, 0)) < 0){
36 | perror("recv");
37 | return EXIT_FAILURE;
38 | }
39 |
40 | buffer[n] = '\0';
41 |
42 | printf("%s", buffer);
43 |
44 | return EXIT_SUCCESS;
45 | }
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/soccergame/README.md:
--------------------------------------------------------------------------------
1 | **EuroThreadSoccer**
2 | Sviluppare un simulatore di match per gli Europei 2024. La partita viene gestita da un arbitro (variable condivisa da entrambe le squadre) tramite una variabile privata “turno” che identifica la squadra in possesso di palla, inizializzata ad “A” (ipotizzando che A identifica la prima squadra e B la seconda).
3 | Ogni squadra quindi sarà un thread avente le variabili:
4 | - Id squadra
5 | - Goal fatti (inizializzata a 0)
6 | Il software effettua un ciclo di 90 iterazioni di un secondo (usando sleep) in cui ad ogni ciclo ogni squadra si comporta in base al seguente schema:
7 | - La squadra è in possesso di palla (sulla base del turno) lancia un dado con 3 possibilità.
8 | 1. La squadra segna un goal (incrementando il numero di goal fatti nella variabile privata della squadra). Cede la palla all’avversario e va in wait.
9 | 2. La squadra sbaglia e perde palla. Cede la palla all’avversario e va in wait.
10 | 3. Mantiene palla
11 | - La squadra non è in possesso palla e non è in attesa, sveglia l’altra squadra e si mette in attesa.
12 |
13 | Alla fine della partita stampare il risultato finale.
14 |
15 | Bonus: se la squadra mantiene il possesso palla più di 3 volte perde cmq il possesso palla
16 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/hello21.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 | import java.util.Random;
3 |
4 | import static java.lang.Thread.sleep;
5 |
6 | public class hello21 {
7 | public static void main(String[] args) throws InterruptedException {
8 | // Main is a deamon
9 | Thread tMain = Thread.currentThread();
10 | System.out.println("Main Thread "+tMain.toString());
11 | // Java Lambda Expression Example: Thread Example
12 | // See https://www.codejava.net/java-core/the-java-language/java-8-lambda-runnable-example
13 |
14 | Runnable fn = () -> {
15 | for (int i=0; i<10; i++) {
16 | System.out.println("Hello from a thread!");
17 | }
18 | };
19 |
20 | // Start a daemon thread to run a task
21 | Thread thread = Thread.ofPlatform().name("Hello").start(fn);
22 |
23 | try {
24 | // aspetta la fine dei thread
25 | thread.join();
26 | } catch (InterruptedException e) { }
27 |
28 | // dopo che il thread t e' concluso, questo thread finisce
29 | System.out.println("T status:"+thread.getState());
30 | System.out.println("This is the end");
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/tcp/echoservermt/Server.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.tcp.echoservermt;
2 |
3 | import java.io.IOException;
4 | import java.net.ServerSocket;
5 | import java.net.Socket;
6 |
7 | public class Server {
8 | static final int PORT = 1050;
9 |
10 | public static void main(String[] args) throws IOException {
11 | ServerSocket serverSocket = new ServerSocket(PORT);
12 | System.out.println("EchoMultiServer: started");
13 | System.out.println("Server Socket: " + serverSocket);
14 |
15 | try {
16 | while(true) {
17 | // bloccante finch� non avviene una connessione:
18 | Socket clientSocket = serverSocket.accept();
19 | System.out.println("Connection accepted: "+ clientSocket);
20 |
21 | try {
22 | new ServerThread(clientSocket);
23 | } catch(IOException e) {
24 | clientSocket.close();
25 | }
26 | }
27 | }
28 | catch (IOException e) {
29 | System.err.println("Accept failed");
30 | System.exit(1);
31 | }
32 | System.out.println("EchoMultiServer: closing...");
33 | serverSocket.close();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/ProvePassate/ValoreAssoluto/consegna.md:
--------------------------------------------------------------------------------
1 | # Titolo: Thread (C/C++ o Java) [Prova in Itinere 18/12/2019]
2 |
3 | ### Tempo a disposizione: 45 minuti
4 |
5 | #### File da consegnare: Tutti i file sorgente prodotti (C/C++ o Java)
6 |
7 | Scrivere in C/C++ o in Java un programma con due thread **T1** e **T2**. I thread hanno una **variabile condivisa x** inizializzata con un intero compreso tra 0 e 10 (*estremi inclusi*).
8 |
9 | Il thread **T1** ha una **variabile privata m** ed esegue un ciclo infinito, comportandosi in ciascun ciclo come segue:
10 | - Attende 100ms
11 | - Genera un valore casuale intero compreso tra 0 e 10 (estremi inclusi) e lo memorizza in **m**
12 | - Se **x** è uguale a `-1` termina l'esecuzione
13 | - Altrimenti, confronta m con la variabile condivisa **x**:
14 | - Se **m** e **x** coincidono stampa un messaggio "RISPOSTA CORRETTA", setta **x** a `-1` e termina l'esecuzione
15 | - Se la differenza in valore assoluto tra **m** ed **x** è **maggiore di 5** stampa il messaggio "risposta MOLTO sbagliata" e si mette in attesa
16 | - Altrimenti, stampa il messaggio "risposta sbagliata"
17 |
18 | Il Thread **T2** invece:
19 | - Attende 300ms
20 | - Sveglia **T1**
21 | - Se **x** è uguale a `-1`, termina l'esecuzione
22 | - Altrimenti, ricomincia dal primo punto
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/pc/producer.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.pc;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/jthread.tar
3 | import java.io.BufferedReader;
4 | import java.io.InputStreamReader;
5 |
6 | public class producer extends Thread{
7 | private container cont;
8 | private final int EOF=-1;
9 | private BufferedReader stdIn=new BufferedReader(new InputStreamReader(System.in));
10 |
11 | public producer(container c) {
12 | cont = c;
13 | }
14 |
15 | public void run() {
16 | System.out.println("P: inizio");
17 | int num;
18 | // chiedo 3 numeri all'utente, tento di inserirne 6 su cont
19 | for (int k=0; k<3; k++) {
20 | try {
21 | System.out.print("P: immettere un numero > ");
22 | num = Integer.parseInt(stdIn.readLine());
23 | cont.put(num);
24 | System.out.println("P: ho inserito "+num);
25 | // la seguente obbliga il produttore ad aspettare che cont sia libero
26 | cont.put(++num);
27 | System.out.println("P: ho inserito "+num);
28 | }
29 | catch(Exception e) { e.printStackTrace(); }
30 | }
31 | System.out.println("P: termino");
32 | cont.put(EOF);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/tcp/echoservermt/ServerThread.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.tcp.echoservermt;
2 |
3 | import java.io.*;
4 | import java.net.Socket;
5 |
6 | public class ServerThread extends Thread{
7 | private static int counter = 0;
8 | private int id = ++counter;
9 |
10 | private Socket socket;
11 | private BufferedReader in;
12 | private PrintWriter out;
13 |
14 | public ServerThread(Socket s) throws IOException {
15 | socket = s;
16 | in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
17 | OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
18 | out = new PrintWriter(new BufferedWriter(osw), true);
19 | start();
20 | System.out.println("ServerThread "+id+": started");
21 | System.out.println("Socket: " + s);
22 | }
23 | public void run() {
24 | try {
25 | while (true) {
26 | String str = in.readLine();
27 | if (str.equals("END")) break;
28 | System.out.println("ServerThread "+id+": echoing -> " + str);
29 | out.println(str);
30 | }
31 | System.out.println("ServerThread "+id+": closing...");
32 | } catch (IOException e) {}
33 | try {
34 | socket.close();
35 | } catch(IOException e) {}
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/nio/sampleapp/Client.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.nio.sampleapp;
2 | import java.io.IOException;
3 | import java.net.InetSocketAddress;
4 | import java.nio.ByteBuffer;
5 | import java.nio.channels.AsynchronousSocketChannel;
6 | import java.util.concurrent.ExecutionException;
7 | import java.util.concurrent.Future;
8 |
9 | public class Client {
10 | public static void main(String[] args){
11 | try (AsynchronousSocketChannel client = AsynchronousSocketChannel.open()) {
12 | Future result = client.connect(new InetSocketAddress("127.0.0.1", 1234));
13 | result.get();
14 | String str= "Hello! How are you?";
15 | ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
16 | Future writeval = client.write(buffer);
17 | System.out.println("Writing to server: "+str);
18 | writeval.get();
19 | buffer.flip();
20 | Future readval = client.read(buffer);
21 | System.out.println("Received from server: " +new String(buffer.array()).trim());
22 | readval.get();
23 | buffer.clear();
24 | }
25 | catch (ExecutionException | IOException e) {
26 | e.printStackTrace();
27 | }
28 | catch (InterruptedException e) {
29 | System.out.println("Disconnected from the server.");
30 | }
31 | }
32 | }
33 |
34 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/udp/filestreamer/DatagramUtility.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.udp.filestreamer;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/socketJ.zip
3 |
4 | /* DatagramUtility.java
5 |
6 | Classe usata per definire alcuni metodi utili nella gestione dei datagrammi,
7 | utilizzati sia dal client che dal server.
8 |
9 | */
10 |
11 | import java.io.*;
12 | import java.net.*;
13 | import java.util.*;
14 |
15 | public class DatagramUtility {
16 | // metodo per creare un pacchetto da una stringa
17 | static protected DatagramPacket buildPacket(InetAddress addr, int port, String msg) throws IOException{
18 | ByteArrayOutputStream boStream = new ByteArrayOutputStream();
19 | DataOutputStream doStream = new DataOutputStream(boStream);
20 | doStream.writeUTF(msg);
21 | byte[] data = boStream.toByteArray();
22 | return new DatagramPacket(data, data.length, addr, port);
23 | // per la creazione di un pacchetto da inviare e' necessario usare il costruttore con destinatario
24 | }
25 |
26 | // metodo per recuperare una stringa da un pacchetto
27 | static protected String getContent(DatagramPacket dp) throws IOException{
28 | ByteArrayInputStream biStream = new ByteArrayInputStream(dp.getData(), 0, dp.getLength());
29 | DataInputStream diStream = new DataInputStream(biStream);
30 | String msg = diStream.readUTF();
31 | return msg;
32 | }
33 | }
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/asyncronous_communication/Logger.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.asyncronous_communication;
2 |
3 | import java.net.Socket;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 |
7 | public class Logger {
8 | private static Logger instance;
9 | private List list_sock = new ArrayList();
10 |
11 | private Logger() {}
12 |
13 | /**
14 | * Ritorna l'unica istanza del logger
15 | *
16 | * @return istanza del logger
17 | */
18 | public static Logger getIstance() {
19 | if (instance == null)
20 | instance = new Logger();
21 |
22 | return instance;
23 | }
24 |
25 | /**
26 | * Aggiorna la lista degli utenti connessi
27 | *
28 | * @param sock Socket passata per aggiornare la lista del log
29 | */
30 | public static void update(Socket sock) {
31 | instance.list_sock.add(sock);
32 | }
33 |
34 | /**
35 | * Elimina un utente che si è disconnesso dal server
36 | *
37 | * @param socket Socket da eliminare dalla lista poichè ha chiuso la connessione
38 | */
39 | public static void delete_user(Socket socket) {
40 | instance.list_sock.remove(socket);
41 | }
42 |
43 |
44 | /**
45 | * Ritorna il log attuale
46 | *
47 | * @return lista del log
48 | */
49 | public static List getLog() {
50 | return instance.list_sock;
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/ProvePassate/Cubo/client.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 |
8 | #define BUFFER_SIZE 16
9 |
10 | int main(int argc, char** argv){
11 | int sockfd;
12 | struct sockaddr_in remote_addr;
13 | socklen_t len = sizeof(struct sockaddr_in);
14 | char buffer[BUFFER_SIZE];
15 |
16 | if(argc != 3){
17 | printf("Usage: ./%s \n", basename(argv[0]));
18 | return EXIT_FAILURE;
19 | }
20 |
21 | if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
22 | perror("socket()");
23 | return EXIT_FAILURE;
24 | }
25 |
26 | memset(&remote_addr, 0, len);
27 | remote_addr.sin_addr.s_addr = inet_addr(argv[1]);
28 | remote_addr.sin_port = htons(atoi(argv[2]));
29 | remote_addr.sin_family = AF_INET;
30 |
31 | if((connect(sockfd, (struct sockaddr*)&remote_addr, len)) < 0){
32 | perror("connect()");
33 | return EXIT_FAILURE;
34 | }
35 |
36 | printf("Inserisci un numero e il Server ti calcolera' il suo cubo: ");
37 | fgets(buffer, BUFFER_SIZE, stdin);
38 |
39 | send(sockfd, buffer, strlen(buffer), 0);
40 |
41 | int n = recv(sockfd, buffer, BUFFER_SIZE, 0);
42 |
43 | if (n < BUFFER_SIZE) {
44 | buffer[n] = '\0';
45 | }
46 |
47 | printf("Risposta Server: %d\n", atoi(buffer));
48 |
49 | close(sockfd);
50 |
51 | return EXIT_SUCCESS;
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/dicegame/JackpotRefiller.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.dicegame;
2 |
3 | public class JackpotRefiller extends Thread {
4 | private Banco banco;
5 | private int refillAmount;
6 |
7 | public JackpotRefiller(Banco banco, int refillAmount) {
8 | this.banco = banco;
9 | this.refillAmount = refillAmount;
10 | }
11 |
12 | @Override
13 | public void run() {
14 | while (true) {
15 | if (banco.getMatchesCounter()==0) {
16 | System.out.println("[BANCO] no more games available! Bye!");
17 | banco.resumeOtherGames();
18 | break; // If there are no more matches, stop playing
19 | }
20 |
21 | if (banco.getNumPlayers()==0) {
22 | System.out.println("[BANCO] no more players available! Bye!");
23 | banco.resumeOtherGames();
24 | break;
25 | }
26 |
27 | // What happens if all players have no money ?
28 | if (banco.getJackpot() < 3) {
29 | banco.addToJackpot(refillAmount);
30 | System.out.println("[BANCO] \uD83D\uDCB0 Refilled " + refillAmount + " coins in the jackpot");
31 | banco.resumeOtherGames();
32 | }
33 |
34 | try {
35 | Thread.sleep(5000); // Wait 5 second
36 | } catch (InterruptedException e) {
37 | e.printStackTrace();
38 | }
39 | }
40 | }
41 |
42 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Examples Sockets
2 |
3 | ## SimpleScraper
4 |
5 |
6 | ## Socket Stream
7 | Server
8 |
9 | ``sh
10 | java -cp target/tswd-java-examples-1.0-SNAPSHOT.jar edu.unict.tswd.socket.tcp.echoserver.EchoServer
11 | ``
12 |
13 | Client
14 |
15 | ``sh
16 | java -cp target/tswd-java-examples-1.0-SNAPSHOT.jar edu.unict.tswd.socket.tcp.echoserver.EchoClient
17 | ``
18 |
19 | ## Socket UDP Multicast
20 | Server
21 | ``sh
22 | java -cp target/tswd-java-examples-1.0-SNAPSHOT.jar edu.unict.tswd.socket.udp.filestreamer.MulticastServer
23 | ``
24 |
25 | Client 1
26 | ``sh
27 | java -cp target/tswd-java-examples-1.0-SNAPSHOT.jar edu.unict.tswd.socket.udp.filestreamer.MulticastClient
28 | ``
29 |
30 | Client 2
31 | ``sh
32 | java -cp target/tswd-java-examples-1.0-SNAPSHOT.jar edu.unict.tswd.socket.udp.filestreamer.MulticastClient
33 | ``
34 |
35 | ## Socket UDP LineReader
36 | Server
37 | ``sh
38 | java -cp target/tswd-java-examples-1.0-SNAPSHOT.jar edu.unict.tswd.socket.udp.filestreamer.LineServer
39 | ``
40 |
41 | Server
42 |
43 | ``sh
44 | java -cp target/tswd-java-examples-1.0-SNAPSHOT.jar edu.unict.tswd.socket.udp.filestreamer.LineClient
45 | ``
46 |
47 | ## NIO ?
48 |
49 | java -cp target/tswd-java-examples-1.0-SNAPSHOT.jar edu.unict.tswd.socket.nio.sampleapp.Server
50 |
51 | java -cp target/tswd-java-examples-1.0-SNAPSHOT.jar edu.unict.tswd.socket.nio.sampleapp.Client
52 | java -cp target/tswd-java-examples-1.0-SNAPSHOT.jar edu.unict.tswd.socket.nio.sampleapp.Client
53 |
54 | Docker
55 |
56 | docker build . -t unict:tswd-java-examples
57 | docker run -t unict:tswd-java-examples edu.unict.tswd.socket.udp.filestreamer.MulticastClient
58 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/ProvePassate/Mul/consegna.md:
--------------------------------------------------------------------------------
1 | # Socket (C o Java)
2 |
3 | - Realizzare un server (in C o in Java) chiamato _Server A_ che si metta in ascolto sul port `7777` per ricevere una stringa `str` composta da una **sequenza di lunghezza arbitraria di caratteri numerici** da (_0 a 9_) e terminata dal carattere `\n`. Il server dovrà quindi stampare il messaggio ricevuto sullo standard output. Testare il server usando `telnet`
4 |
5 | - Estendere le funzionalità dal server definito al punto precedente realizzando un secondo server chiamato _Server B_ che oltre a stampare il messaggio ricevuto sullo standard output, lo **invia come risposta al client** (_senza modificarlo_). Testare il server usando `telnet`.
6 |
7 | - Estendere le funzionalità dal server definito al punto precedente realizzando un terzo server chiamato _Server C_ che oltre a stampare il messaggio ricevuto sullo standard output, lo passa ad un metodo `int MUL(String str)` che per ora **restituisce sempre 0** per qualunque parametro di input str. Il risultato del metodo deve quindi essere inviato come messaggio di risposta al client. Testare il server usando `telnet`.
8 |
9 | - Estendere le funzionalità dal server definito al punto precedente realizzando un quarto server chiamato _Server D_ modificando il comportamento del metodo `int MUL(String str)` che dovrà restituire **il prodotto delle singole cifre numeriche** presenti nella stringa in input, ad esempio per la stringa `1234` restituirà l’intero `24`. Il risultato del metodo deve quindi essere inviato come messaggio di risposta al client. Testare il server usando `telnet`.
10 |
11 | - _(Opzionale)_ Realizzare un semplice client per testare i server creati ai punti precedenti
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/ProvePassate/Mul/ServerA.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.ProvePassate.Mul;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.IOException;
5 | import java.io.InputStreamReader;
6 | import java.io.PrintWriter;
7 | import java.net.ServerSocket;
8 | import java.net.Socket;
9 |
10 | public class ServerA {
11 | private static final int PORT = 7777;
12 |
13 | public static void main(String[] args) {
14 | ServerSocket serverSocket = null;
15 |
16 | try{
17 | serverSocket = new ServerSocket(PORT);
18 | } catch(IOException e){
19 | System.out.println("serverSocket");
20 | System.exit(1);
21 | }
22 |
23 | System.out.println(serverSocket + "started...");
24 |
25 | Socket clientSocket = null;
26 | BufferedReader in = null;
27 | PrintWriter out = null;
28 |
29 | try{
30 | clientSocket = serverSocket.accept();
31 | in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
32 | out = new PrintWriter(clientSocket.getOutputStream(), true);
33 |
34 | String buffer = in.readLine();
35 | System.out.println("ServerA received: " + buffer);
36 |
37 | } catch(IOException e){
38 | System.out.println("accept");
39 | System.exit(1);
40 | }
41 |
42 |
43 | try{
44 | in.close();
45 | out.close();
46 | clientSocket.close();
47 | serverSocket.close();
48 | } catch(IOException e){
49 | System.out.println("close");
50 | System.exit(1);
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/hellothread/hello4.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.hellothread;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/jthread.tar
3 | import java.util.Random;
4 |
5 | import static java.lang.Thread.sleep;
6 |
7 | public class hello4 {
8 | public static void main(String[] args) throws InterruptedException {
9 | // Main is a deamon
10 | Thread tMain = Thread.currentThread();
11 | System.out.println("Main Thread "+tMain.toString());
12 | myThread4 t = new myThread4();
13 | // Start thread
14 | t.start();
15 | // Create another thread
16 | myRunnable4 myRunnable = new myRunnable4();
17 | Thread myRunnableThread = new Thread(myRunnable);
18 | // Start
19 | myRunnableThread.start();
20 |
21 | // In parallel here
22 | for (int i = 0; i < 5000; i++) {
23 | System.out.println("<");
24 | sleep(new Random().nextInt(5)); // Poor Ascii ART
25 | System.out.println("T status:"+t.getState());
26 | System.out.println("T2 status:"+myRunnableThread.getState());
27 | //if ( t.isAlive() ) System.out.print("alive");
28 | }
29 | System.out.println("");
30 |
31 | try {
32 | // aspetta la fine dei thread
33 | t.join();
34 | myRunnableThread.join();
35 | } catch (InterruptedException e) { }
36 |
37 | // dopo che il thread t e' concluso, questo thread finisce
38 | System.out.println("T status:"+t.getState());
39 | System.out.println("myRunnableThread status:"+myRunnableThread.getState());
40 | System.out.println("This is the end");
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/tcp/finger/finger.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.tcp.finger;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.InputStreamReader;
5 | import java.io.PrintStream;
6 | import java.net.Socket;
7 |
8 | public class finger {
9 | public static void main( String[] args )
10 | {
11 | if( args.length < 2 )
12 | {
13 | System.out.println( "Usage: finger " );
14 | System.exit( 0 );
15 | }
16 | String server = args[ 0 ];
17 | String name = args[ 1 ];
18 |
19 | System.out.println( "Loading contents of URL: " + server + name);
20 |
21 | try
22 | {
23 | // Connect to the server
24 | Socket socket = new Socket(server,79);
25 |
26 | // Create input and output streams to read from and write to the server
27 | PrintStream out = new PrintStream( socket.getOutputStream() );
28 | BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
29 |
30 |
31 | out.print( name+"\r\n" );
32 | out.print("\r\n");
33 | System.out.println( "Get Response");
34 | // Read data from the server until we finish reading the document
35 | String line = in.readLine();
36 | while( line != null )
37 | {
38 | System.out.println( line );
39 | line = in.readLine();
40 | }
41 |
42 | // Close our streams
43 | in.close();
44 | out.close();
45 | socket.close();
46 | }
47 | catch( Exception e )
48 | {
49 | e.printStackTrace();
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/ProvePassate/Mul/ServerB.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.ProvePassate.Mul;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.IOException;
5 | import java.io.InputStreamReader;
6 | import java.io.PrintWriter;
7 | import java.net.ServerSocket;
8 | import java.net.Socket;
9 |
10 | public class ServerB {
11 | private static final int PORT = 7777;
12 |
13 | public static void main(String[] args) {
14 | ServerSocket serverSocket = null;
15 |
16 | try{
17 | serverSocket = new ServerSocket(PORT);
18 | } catch(IOException e){
19 | System.out.println("serverSocket");
20 | System.exit(1);
21 | }
22 |
23 | System.out.println(serverSocket + "started...");
24 |
25 | Socket clientSocket = null;
26 | BufferedReader in = null;
27 | PrintWriter out = null;
28 |
29 | try{
30 | clientSocket = serverSocket.accept();
31 | in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
32 | out = new PrintWriter(clientSocket.getOutputStream(), true);
33 |
34 | String buffer = in.readLine();
35 | System.out.println("ServerB received: " + buffer);
36 | out.println("ServerB answer: " + buffer);
37 |
38 | } catch(IOException e){
39 | System.out.println("accept");
40 | System.exit(1);
41 | }
42 |
43 |
44 | try{
45 | in.close();
46 | out.close();
47 | clientSocket.close();
48 | serverSocket.close();
49 | } catch(IOException e){
50 | System.out.println("close");
51 | System.exit(1);
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/ProvePassate/Mul/ServerC.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.ProvePassate.Mul;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.IOException;
5 | import java.io.InputStreamReader;
6 | import java.io.PrintWriter;
7 | import java.net.ServerSocket;
8 | import java.net.Socket;
9 |
10 | public class ServerC {
11 | private static final int PORT = 7777;
12 |
13 | private static int MUL(String str){
14 | return 0;
15 | }
16 |
17 | public static void main(String[] args) {
18 | ServerSocket serverSocket = null;
19 |
20 | try{
21 | serverSocket = new ServerSocket(PORT);
22 | } catch(IOException e){
23 | System.out.println("serverSocket");
24 | System.exit(1);
25 | }
26 |
27 | System.out.println(serverSocket + "started...");
28 |
29 | Socket clientSocket = null;
30 | BufferedReader in = null;
31 | PrintWriter out = null;
32 |
33 | try{
34 | clientSocket = serverSocket.accept();
35 | in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
36 | out = new PrintWriter(clientSocket.getOutputStream(), true);
37 |
38 | String buffer = in.readLine();
39 | System.out.println("ServerC received: " + buffer);
40 | out.println("ServerC answer: " + MUL(buffer));
41 |
42 | } catch(IOException e){
43 | System.out.println("accept");
44 | System.exit(1);
45 | }
46 |
47 |
48 | try{
49 | in.close();
50 | out.close();
51 | clientSocket.close();
52 | serverSocket.close();
53 | } catch(IOException e){
54 | System.out.println("close");
55 | System.exit(1);
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/dicegame/Banco.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.dicegame;
2 |
3 | public class Banco {
4 | private int jackpot; // Quantity of money available to be won
5 | private int matchesCounter; // Max number of mathes
6 | private int numPlayers; // used to count how ma
7 |
8 | public Banco(int jackpot, int matchesCounter) {
9 | this.jackpot = jackpot;
10 | this.matchesCounter = matchesCounter;
11 | this.numPlayers=0;
12 | }
13 |
14 | public synchronized void increaseNumPlayers() {
15 | numPlayers++;
16 | }
17 |
18 | public synchronized void decreaseNumPlayers() {
19 | numPlayers--;
20 | // Check if is 0 or less signal to wakeup ?
21 | ;
22 | }
23 |
24 | public int getNumPlayers() {
25 | return(numPlayers);
26 | }
27 |
28 | public synchronized int getJackpot() {
29 | return jackpot;
30 | }
31 |
32 | public synchronized void addToJackpot(int jackpot) {
33 | this.jackpot += jackpot;
34 | }
35 |
36 | public synchronized int getMoney(String name, int money) {
37 | while (this.jackpot - money <= 0) {
38 | try {
39 | System.out.println("["+name+"] Not enough money in the jackpot, waiting...");
40 | wait();
41 | } catch (InterruptedException e) {
42 | e.printStackTrace();
43 | }
44 | } // Here we are sure that there is enough money in the jackpot
45 | this.jackpot -= money; // Update jackpot;
46 | return money;
47 | }
48 |
49 | public synchronized void resumeOtherGames() {
50 | notifyAll();
51 | }
52 |
53 | public synchronized void decreaseMatchCounters() {
54 | matchesCounter--;
55 | }
56 |
57 | public int getMatchesCounter() {
58 | return matchesCounter;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/tcp/biblioteca/Client.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.tcp.biblioteca;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.IOException;
5 | import java.io.InputStreamReader;
6 | import java.io.PrintWriter;
7 | import java.net.InetAddress;
8 | import java.net.Socket;
9 | import java.net.UnknownHostException;
10 |
11 | public class Client{
12 | public static void main(String[] args) {
13 | if(args.length != 1){
14 | System.out.println("Usage: java Client ");
15 | System.exit(1);
16 | }
17 |
18 | InetAddress serverAddr = null;
19 | try{
20 | serverAddr = InetAddress.getByName(args[0]);
21 | } catch(UnknownHostException u){
22 | System.out.println("Not valid address");
23 | System.exit(1);
24 | }
25 |
26 | Socket socket = null;
27 | BufferedReader in = null, stdIn = null;
28 | PrintWriter out = null;
29 |
30 |
31 | try{
32 | socket = new Socket(serverAddr, BibliotecaServer.PORT);
33 | in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
34 | out = new PrintWriter(socket.getOutputStream(), true);
35 | stdIn = new BufferedReader(new InputStreamReader(System.in));
36 |
37 | String bookName = stdIn.readLine();
38 | out.println(bookName);
39 | System.out.print("Status: ");
40 | System.out.println(in.readLine());
41 |
42 |
43 | } catch(IOException e){
44 | System.out.println("Error: Server off");
45 | System.exit(1);
46 | }
47 |
48 | try{
49 | in.close();
50 | out.close();
51 | socket.close();
52 | stdIn.close();
53 | } catch(IOException e){
54 | System.out.println("close() error");
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/ProvePassate/Cubo/Server.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.ProvePassate.Cubo;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.IOException;
5 | import java.io.InputStreamReader;
6 | import java.io.PrintWriter;
7 | import java.net.ServerSocket;
8 | import java.net.Socket;
9 |
10 | public class Server {
11 | private static final int PORT = 3333;
12 |
13 | public static int cubo(int n){
14 | return n*n*n;
15 | }
16 |
17 | public static void main(String[] args) {
18 | ServerSocket socket = null;
19 |
20 | try{
21 | socket = new ServerSocket(PORT);
22 | } catch (IOException e){
23 | System.out.println("New socket!");
24 | e.printStackTrace();
25 | }
26 |
27 | System.out.println("Server started \n" + socket);
28 |
29 | Socket clientSocket = null;
30 | BufferedReader in = null;
31 | PrintWriter out = null;
32 |
33 | try{
34 | clientSocket = socket.accept();
35 | in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
36 | out = new PrintWriter(clientSocket.getOutputStream(), true);
37 |
38 | String text = in.readLine();
39 | System.out.println("Received: "+ text);
40 |
41 | int number = Integer.parseInt(text);
42 |
43 | out.println(cubo(number));
44 | } catch(IOException e){
45 | System.out.println("accept()");
46 | e.printStackTrace();
47 | }
48 |
49 | System.out.println("Closing connection..");
50 |
51 | try{
52 | in.close();
53 | out.close();
54 | socket.close();
55 | clientSocket.close();
56 | } catch(IOException e){
57 | System.out.println("close()");
58 | e.printStackTrace();
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/nio/sampleapp/Server.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.nio.sampleapp;
2 | // Credits
3 | // https://www.developer.com/design/understanding-asynchronous-socket-channels-in-java/
4 | import java.net.InetSocketAddress;
5 | import java.nio.ByteBuffer;
6 | import java.nio.channels.AsynchronousServerSocketChannel;
7 | import java.nio.channels.AsynchronousSocketChannel;
8 | import java.util.concurrent.Future;
9 | import java.util.concurrent.TimeUnit;
10 |
11 | public class Server {
12 | public static void main(String[] args){
13 | try (AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open()) {
14 | server.bind(new InetSocketAddress("127.0.0.1", 1234));
15 |
16 | System.out.println("Not waiting");
17 | while(true) {
18 | System.out.println("Loop");
19 | Future acceptCon = server.accept();
20 | AsynchronousSocketChannel client = acceptCon.get(10, TimeUnit.SECONDS);
21 | System.out.println("Connection"+client);
22 | if ((client != null) && (client.isOpen())) {
23 | ByteBuffer buffer = ByteBuffer.allocate(1024);
24 | Future readval = client.read(buffer);
25 | System.out.println("Received from client: " + new String(buffer.array()).trim());
26 | readval.get();
27 | buffer.flip();
28 | String str = "I'm fine. Thank you!";
29 | Future writeVal = client.write(ByteBuffer.wrap(str.getBytes()));
30 | System.out.println("Writing back to client: " + str);
31 | writeVal.get();
32 | buffer.clear();
33 | }
34 | client.close();
35 | }
36 | } catch (Exception e) {
37 | e.printStackTrace();
38 | }
39 | }
40 | }
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/nio/baeldung/EchoClient.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.nio.baeldung;
2 |
3 | import java.io.IOException;
4 | import java.net.InetSocketAddress;
5 | import java.nio.ByteBuffer;
6 | import java.nio.channels.SocketChannel;
7 |
8 | public class EchoClient {
9 | private static SocketChannel client;
10 | private static ByteBuffer buffer;
11 | private static EchoClient instance;
12 |
13 | public static EchoClient start() {
14 | if (instance == null)
15 | instance = new EchoClient();
16 |
17 | return instance;
18 | }
19 |
20 | public static void stop() throws IOException {
21 | client.close();
22 | buffer = null;
23 | }
24 |
25 | private EchoClient() {
26 | try {
27 | client = SocketChannel.open(new InetSocketAddress("localhost", 5454));
28 | buffer = ByteBuffer.allocate(256);
29 | } catch (IOException e) {
30 | e.printStackTrace();
31 | }
32 | }
33 |
34 | public String sendMessage(String msg) {
35 | buffer = ByteBuffer.wrap(msg.getBytes());
36 | String response = null;
37 | try {
38 | client.write(buffer);
39 | buffer.clear();
40 | client.read(buffer);
41 | response = new String(buffer.array()).trim();
42 | System.out.println("response=" + response);
43 | buffer.clear();
44 | } catch (IOException e) {
45 | e.printStackTrace();
46 | }
47 | return response;
48 |
49 | }
50 |
51 | public static void main(String... args) throws IOException, InterruptedException {
52 | EchoClient client=start();
53 | String resp1 = client.sendMessage("hello");
54 | String resp2 = client.sendMessage("world");
55 | // String resp3 = client.sendMessage("POISON_PILL");
56 | System.out.println(resp1 + " " + resp2);
57 | EchoClient.stop();
58 | }
59 | }
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/ProvePassate/Mul/ServerD.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.ProvePassate.Mul;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.IOException;
5 | import java.io.InputStreamReader;
6 | import java.io.PrintWriter;
7 | import java.net.ServerSocket;
8 | import java.net.Socket;
9 |
10 | public class ServerD {
11 | private static final int PORT = 7777;
12 |
13 | private static int MUL(String str){
14 | int res = 1;
15 | for(int i=0; i < str.length(); i++){
16 | res *= Character.getNumericValue(str.charAt(i));
17 | }
18 |
19 | return res;
20 | }
21 |
22 | public static void main(String[] args) {
23 | ServerSocket serverSocket = null;
24 |
25 | try{
26 | serverSocket = new ServerSocket(PORT);
27 | } catch(IOException e){
28 | System.out.println("serverSocket");
29 | System.exit(1);
30 | }
31 |
32 | System.out.println(serverSocket + "started...");
33 |
34 | Socket clientSocket = null;
35 | BufferedReader in = null;
36 | PrintWriter out = null;
37 |
38 | try{
39 | clientSocket = serverSocket.accept();
40 | in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
41 | out = new PrintWriter(clientSocket.getOutputStream(), true);
42 |
43 | String buffer = in.readLine();
44 | System.out.println("ServerD received: " + buffer);
45 | out.println("ServerD answer: " + MUL(buffer));
46 |
47 | } catch(IOException e){
48 | System.out.println("accept");
49 | System.exit(1);
50 | }
51 |
52 |
53 | try{
54 | in.close();
55 | out.close();
56 | clientSocket.close();
57 | serverSocket.close();
58 | } catch(IOException e){
59 | System.out.println("close");
60 | System.exit(1);
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/asyncronous_communication/Server.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.asyncronous_communication;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.PrintWriter;
5 | import java.net.ServerSocket;
6 | import java.net.Socket;
7 |
8 | /**
9 | * Server che mantiene un log dei client che si sono connessi
10 | *
11 | * Comandi:
12 | *
13 | * 1. LOG -> Il client può chiedere di conoscere tutti gli utenti connessi fino a quel momento
14 | * 2. QUIT -> chiudere la propria connessione con il server
15 | */
16 | public class Server {
17 | private Worker log;
18 | private ServerSocket serv_sock;
19 | private Socket client_sock;
20 | private int port = 8000;
21 |
22 | public Server() {
23 | start_server();
24 | run();
25 | }
26 |
27 | /**
28 | * Metodo che inizializza la socket del server
29 | */
30 | public void start_server() {
31 | try {
32 | serv_sock = new ServerSocket(port);
33 | serv_sock.setReuseAddress(true);
34 | } catch (Exception e) {
35 | e.printStackTrace();
36 | }
37 | }
38 |
39 | /**
40 | * Metodo in cui il server accetta nuove connessioni e lascia gestire le richieste a un worker
41 | */
42 | public void run() {
43 | while (true) {
44 | try {
45 | if (serv_sock != null) {
46 | client_sock = serv_sock.accept();
47 | log = new Worker(client_sock, this);
48 | log.start();
49 | } else {
50 | System.out.println("serv_sock is null");
51 | System.exit(-1);
52 | }
53 | } catch (Exception e) {
54 | e.printStackTrace();
55 | }
56 | }
57 | }
58 |
59 | /**
60 | * Metodo che chiude la socket del server
61 | */
62 | public void close_connection() {
63 | try {
64 | serv_sock.close();
65 | } catch (Exception e) {
66 | e.printStackTrace();
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/tcp/simplescraper/webscraper.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.tcp.simplescraper;
2 | // Credits https://www.infoworld.com/article/2853780/socket-programming-for-scalable-systems.html
3 |
4 | import java.io.BufferedReader;
5 | import java.io.InputStreamReader;
6 | import java.io.PrintStream;
7 | import java.net.Socket;
8 |
9 | public class webscraper {
10 | public static void main( String[] args )
11 | {
12 | if( args.length < 2 )
13 | {
14 | System.out.println( "Usage: webscraper " );
15 | System.exit( 0 );
16 | }
17 | String server = args[ 0 ];
18 | String path = args[ 1 ];
19 |
20 | System.out.println( "Loading contents of URL: " + server + path);
21 |
22 | try
23 | {
24 | // Connect to the server
25 | Socket socket = new Socket(server,443);
26 |
27 | // Create input and output streams to read from and write to the server
28 | PrintStream out = new PrintStream( socket.getOutputStream() );
29 | BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
30 |
31 | // Follow the HTTP protocol of GET HTTP/1.1
32 | System.out.print( "GET " + path + " HTTP/1.1\r\n" );
33 | out.print( "GET " + path + " HTTP/1.1\r\n" );
34 | // add header host
35 | System.out.print( "Host: " + server+"\r\n");
36 | out.print( "Host: " + server+"\r\n");
37 | out.print("\r\n");
38 | System.out.println( "Get Response");
39 | // Read data from the server until we finish reading the document
40 | String line = in.readLine();
41 | while( line != null )
42 | {
43 | System.out.println( line );
44 | line = in.readLine();
45 | }
46 |
47 | // Close our streams
48 | in.close();
49 | out.close();
50 | socket.close();
51 | }
52 | catch( Exception e )
53 | {
54 | e.printStackTrace();
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/tcp/echoservermt/ClientThread.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.tcp.echoservermt;
2 |
3 | import java.io.*;
4 | import java.net.InetAddress;
5 | import java.net.Socket;
6 |
7 | public class ClientThread extends Thread {
8 | private Socket socket;
9 | private BufferedReader in;
10 | private PrintWriter out;
11 | private static int counter = 0;
12 | private int id = counter++;
13 | private static int threadcount = 0;
14 |
15 | public static int threadCount() {
16 | return threadcount;
17 | }
18 |
19 | public ClientThread(InetAddress addr) {
20 | threadcount++;
21 |
22 | try {
23 | socket = new Socket(addr, Server.PORT);
24 | System.out.println("EchoClient n "+id+": started");
25 | System.out.println("Client Socket: "+ socket);
26 | } catch(IOException e) {}
27 | // Se la creazione della socket fallisce non � necessario fare nulla
28 |
29 | try {
30 | InputStreamReader isr = new InputStreamReader(socket.getInputStream());
31 | in = new BufferedReader(isr);
32 | OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
33 | out = new PrintWriter(new BufferedWriter(osw), true);
34 | start();
35 | } catch(IOException e1) {
36 | // in seguito ad ogni fallimento la socket deve essere chiusa, altrimenti
37 | // verr� chiusa dal metodo run() del thread
38 | try {
39 | socket.close();
40 | } catch(IOException e2) {}
41 | }
42 | }
43 |
44 | public void run() {
45 | try {
46 | for(int i =0;i <10; i++) {
47 | out.println("client "+id +" msg "+i);
48 | System.out.println("Msg sent: client "+id+" msg"+i);
49 | String str = in.readLine();
50 | System.out.println("Echo: "+str);
51 | }
52 | out.println("END");
53 | } catch(IOException e) {}
54 | try {
55 | System.out.println("Client "+id+" closing...");
56 | socket.close();
57 | } catch(IOException e) {}
58 | threadcount--;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/tcp/echoserver/EchoServer.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.tcp.echoserver;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/socketJ.zip
3 |
4 | import java.io.*;
5 | import java.net.*;
6 |
7 | public class EchoServer {
8 | public static final int PORT = 1050; // Server port
9 | public static final String SECRET = "mischief-managed"; // Server secret
10 |
11 | public static void main(String[] args) {
12 | ServerSocket serverSocket = null;
13 | try {
14 | serverSocket = new ServerSocket(PORT);
15 | } catch (IOException e) {
16 | e.printStackTrace();
17 | }
18 | System.out.println("EchoServer: started ");
19 | System.out.println("Server Socket: " + serverSocket);
20 | Socket clientSocket=null;
21 | BufferedReader in=null;
22 | PrintWriter out=null;
23 | try {
24 | // Waits until connection is available
25 | clientSocket = serverSocket.accept();
26 | System.out.println("Connection accepted: "+ clientSocket);
27 |
28 | // Input Stream
29 | in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
30 |
31 | // Output Stream
32 | out = new PrintWriter(clientSocket.getOutputStream(), true);
33 |
34 | String inputLine;
35 | // Loop, "mischief-managed" will close it
36 | while ((inputLine = in.readLine()) != null) {
37 | if (inputLine.equals(SECRET))
38 | break;
39 | System.out.println("Echoing: " + inputLine);
40 | out.println(inputLine); // Send it back
41 | }
42 | }
43 | catch (IOException e) {
44 | System.err.println("Accept failed");
45 | System.exit(1);
46 | }
47 | // Closing all flows
48 | System.out.println("EchoServer: closing...");
49 |
50 | try {
51 | out.close();
52 | in.close();
53 | clientSocket.close();
54 | serverSocket.close();
55 | } catch (IOException e) {
56 | System.out.println("Errorclosing...");
57 | e.printStackTrace();
58 | }
59 |
60 | }
61 | }
62 |
63 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/ProvePassate/ValoreAssoluto/MyThread.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.ProvePassate.ValoreAssoluto;
2 |
3 | import java.util.Random;
4 |
5 | public class MyThread extends Thread {
6 | Random rand = new Random();
7 | private int m;
8 | private int tid;
9 | Shared shared;
10 |
11 | public MyThread(Shared shared, int tid){
12 | this.shared = shared;
13 | this.tid = tid;
14 | }
15 |
16 | @Override
17 | public void run(){
18 | //T1
19 | if(tid == 1){
20 | while(true){
21 | try {
22 | Thread.sleep(100);
23 | } catch (InterruptedException e){
24 | System.out.println("sleep()");
25 | e.printStackTrace();
26 | }
27 | m = rand.nextInt(11);
28 |
29 | if(shared.getX() == -1){
30 | break;
31 | }
32 |
33 | if (m == shared.getX()){
34 | System.out.println("RISPOSTA CORRETTA");
35 | shared.setX(-1);
36 | break;
37 | }
38 |
39 | if(Math.abs(this.m - shared.getX()) > 5){
40 | System.out.println("risposta MOLTO sbagliata");
41 | try{
42 | shared.sharedWait();
43 | } catch(InterruptedException e){
44 | System.out.println("sharedWait()");
45 | e.printStackTrace();
46 | }
47 | continue;
48 | }
49 | else{
50 | System.out.println("risposta sbagliata");
51 | }
52 | }
53 | }
54 | // T2
55 | else if (tid == 2){
56 | while(true){
57 | try {
58 | Thread.sleep(300);
59 | } catch (InterruptedException e){
60 | System.out.println("sleep()");
61 | e.printStackTrace();
62 | }
63 | shared.sharedNotify();
64 | if(shared.getX() == -1){
65 | break;
66 | }
67 | }
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/tcp/echoserver/EchoClient.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.tcp.echoserver;
2 |
3 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/socketJ.zip
4 |
5 | import java.io.*;
6 | import java.net.InetAddress;
7 | import java.net.Socket;
8 | import java.net.UnknownHostException;
9 |
10 | public class EchoClient {
11 | public static void main(String[] args) throws IOException {
12 | InetAddress addr;
13 |
14 | if (args.length == 0)
15 | addr = InetAddress.getByName(null);
16 | else addr = InetAddress.getByName(args[0]);
17 |
18 | Socket socket = null;
19 | BufferedReader in = null, stdIn = null;
20 | PrintWriter out = null;
21 |
22 | try {
23 | // Create socket
24 | socket = new Socket(addr, EchoServer.PORT);
25 | System.out.println("EchoClient: started");
26 | System.out.println("Client Socket: " + socket);
27 |
28 | // Input Stream
29 | in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
30 |
31 | // Output Stream
32 | out = new PrintWriter(socket.getOutputStream(), true);
33 |
34 | // Keyboard Input Stream
35 | stdIn = new BufferedReader(new InputStreamReader(System.in));
36 | String userInput;
37 |
38 | // ciclo di lettura da tastiera, invio al server e stampa risposta
39 | while (true) {
40 | userInput = stdIn.readLine();
41 | out.println(userInput);
42 | if (userInput.equals(EchoServer.SECRET)) {
43 | System.out.println("Killing Server with SECRET: " + in.readLine());
44 | break;
45 | }
46 | System.out.println("Server Response: " + in.readLine());
47 | }
48 | } catch (UnknownHostException e) {
49 | System.err.println("Don't know about host " + addr);
50 | System.exit(1);
51 | } catch (IOException e) {
52 | System.err.println("Couldn't get I/O for the connection to: " + addr);
53 | System.exit(1);
54 | }
55 | System.out.println("EchoClient: closing...");
56 | out.close();
57 | in.close();
58 | stdIn.close();
59 | socket.close();
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/udp/filestreamer/LineUtility.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.udp.filestreamer;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/socketJ.zip
3 | /* LineUtility.java
4 | Classe usata per definire alcuni metodi utili nella selezione delle linee di un file
5 | */
6 |
7 | import java.io.*;
8 | import java.net.*;
9 | import java.util.*;
10 |
11 | public class LineUtility {
12 | // metodo per recuperare una certa linea di un certo file
13 | static String getLine(String nomeFile, int numLinea) {
14 | String linea = null;
15 | BufferedReader in = null;
16 | // associazione di uno stream di input al file da cui estrarre le linee
17 | try {
18 | in = new BufferedReader(new FileReader("resources/"+nomeFile));
19 | System.out.println("File aperto: "+nomeFile);
20 | }
21 | catch (FileNotFoundException e) {
22 | System.out.println("File non trovato: ");
23 | e.printStackTrace();
24 | return linea = "File non trovato";
25 | }
26 | try {
27 | for (int i=1; i log = Logger.getIstance().getLog();
46 |
47 | int num_user = 0;
48 | for (Socket el: log) {
49 | out.println("Utente #" + num_user + ": " + el);
50 | num_user++;
51 | }
52 | } catch (Exception e) {
53 | e.printStackTrace();
54 | }
55 | }
56 |
57 | /**
58 | * Corpo del thread
59 | */
60 | public void run() {
61 | try {
62 | in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
63 | out = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()), true);
64 |
65 | String req;
66 | Logger log = Logger.getIstance();
67 |
68 | log.update(sock);
69 | while((req = in.readLine()) != null) {
70 | if (req.equals("QUIT")) {
71 | log.delete_user(sock);
72 | closebuffer();
73 | sock.close();
74 | break;
75 | } else if (req.equals("LOG")) {
76 | printLog();
77 | }else {
78 | out.println("Comando sconosciuto");
79 | }
80 | }
81 | } catch (Exception e) {
82 | e.printStackTrace();
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/resources/saggezza.txt:
--------------------------------------------------------------------------------
1 | Life is wonderful. Without it we'd all be dead.
2 | Daddy, why doesn't this magnet pick up this floppy disk?
3 | Give me ambiguity or give me something else.
4 | I.R.S.: We've got what it takes to take what you've got!
5 | We are born naked, wet and hungry. Then things get worse.
6 | Make it idiot proof and someone will make a better idiot.
7 | He who laughs last thinks slowest!
8 | Always remember you're unique, just like everyone else.
9 | "More hay, Trigger?" "No thanks, Roy, I'm stuffed!"
10 | A flashlight is a case for holding dead batteries.
11 | Lottery: A tax on people who are bad at math.
12 | Error, no keyboard - press F1 to continue.
13 | There's too much blood in my caffeine system.
14 | Artificial Intelligence usually beats real stupidity.
15 | Hard work has a future payoff. Laziness pays off now.
16 | "Very funny, Scotty. Now beam down my clothes."
17 | Puritanism: The haunting fear that someone, somewhere may be happy.
18 | Consciousness: that annoying time between naps.
19 | Don't take life too seriously, you won't get out alive.
20 | I don't suffer from insanity. I enjoy every minute of it.
21 | Better to understand a little than to misunderstand a lot.
22 | The gene pool could use a little chlorine.
23 | When there's a will, I want to be in it.
24 | Okay, who put a "stop payment" on my reality check?
25 | We have enough youth, how about a fountain of SMART?
26 | Programming is an art form that fights back.
27 | "Daddy, what does FORMATTING DRIVE C mean?"
28 | All wiyht. Rho sritched mg kegtops awound?
29 | My mail reader can beat up your mail reader.
30 | Never forget: 2 + 2 = 5 for extremely large values of 2.
31 | Nobody has ever, ever, EVER learned all of WordPerfect.
32 | To define recursion, we must first define recursion.
33 | Good programming is 99% sweat and 1% coffee.
34 | Home is where you hang your @
35 | The E-mail of the species is more deadly than the mail.
36 | A journey of a thousand sites begins with a single click.
37 | You can't teach a new mouse old clicks.
38 | Great groups from little icons grow.
39 | Speak softly and carry a cellular phone.
40 | C:\ is the root of all directories.
41 | Don't put all your hypes in one home page.
42 | Pentium wise; pen and paper foolish.
43 | The modem is the message.
44 | Too many clicks spoil the browse.
45 | The geek shall inherit the earth.
46 | A chat has nine lives.
47 | Don't byte off more than you can view.
48 | Fax is stranger than fiction.
49 | What boots up must come down.
50 | Windows will never cease. (ed. oh sure...)
51 | In Gates we trust. (ed. yeah right....)
52 | Virtual reality is its own reward.
53 | Modulation in all things.
54 | A user and his leisure time are soon parted.
55 | There's no place like http://www.home.com
56 | Know what to expect before you connect.
57 | Oh, what a tangled website we weave when first we practice.
58 | Speed thrills.
59 | Give a man a fish and you feed him for a day; teach him to use the Net and he won't bother you for weeks.
60 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/tcp/biblioteca/BibliotecaServer.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.tcp.biblioteca;
2 |
3 | /*
4 | Realizzare un server che tiene traccia della disponibilità di 10 libri, che possono essere disponibili o in prestito;
5 | riceve delle richieste da parte dei client del tipo "titolo del libro"
6 | e risponde "Disponibile", "In prestito" o "Inesistente" a seconda del titolo richiesto.
7 | */
8 |
9 | import java.net.*;
10 | import java.util.Map;
11 | import java.io.*;
12 |
13 | public class BibliotecaServer {
14 | public static final int PORT = 8080;
15 | private static final Map books = Map.of("1984", "Disponibile",
16 | "Il signore degli anelli", "In prestito",
17 | "Harry Potter", "Disponibile",
18 | "Il codice da Vinci", "In prestito",
19 | "Il nome della rosa", "Disponibile",
20 | "Il piccolo principe", "In prestito",
21 | "Il vecchio e il mare", "In prestito",
22 | "Il gattopardo", "Disponibile",
23 | "Il barone rampante", "Disponibile",
24 | "Il fu Mattia Pascal", "In prestito");
25 |
26 | public static void main(String[] args) throws IOException {
27 | ServerSocket socket = null;
28 | try{
29 | socket = new ServerSocket(BibliotecaServer.PORT);
30 | } catch(IOException e){
31 | System.out.println("ServerSocket failed");
32 |
33 | }
34 | PrintWriter out = null;
35 | BufferedReader in = null;
36 | Socket clientSocket = null;
37 |
38 | try{
39 | clientSocket = socket.accept();
40 |
41 | System.out.println("Connetion " + clientSocket + " accepted");
42 |
43 | in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); //recv
44 | out = new PrintWriter(clientSocket.getOutputStream(), true); // send
45 |
46 | String buffer = in.readLine(); // name of the book
47 | System.out.println("Book requested: " + buffer);
48 |
49 | if(books.get(buffer) == null)
50 | out.println("Non disponibile");
51 | else
52 | out.println(books.get(buffer));
53 | } catch (IOException e){
54 | System.out.println("Accept failed");
55 | System.exit(1);
56 | }
57 |
58 | try{
59 | in.close();
60 | out.close();
61 | clientSocket.close();
62 | } catch(IOException e){
63 | System.out.println("Close failed");
64 | }
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/nio/baeldung/EchoServer.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.nio.baeldung;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.net.InetSocketAddress;
6 | import java.nio.ByteBuffer;
7 | import java.nio.channels.SelectionKey;
8 | import java.nio.channels.Selector;
9 | import java.nio.channels.ServerSocketChannel;
10 | import java.nio.channels.SocketChannel;
11 | import java.util.Iterator;
12 | import java.util.Set;
13 |
14 | public class EchoServer {
15 |
16 | private static final String POISON_PILL = "POISON_PILL";
17 |
18 | public static void main(String[] args) throws IOException {
19 | Selector selector = Selector.open();
20 | ServerSocketChannel serverSocket = ServerSocketChannel.open();
21 | serverSocket.bind(new InetSocketAddress("localhost", 5454));
22 | serverSocket.configureBlocking(false);
23 | serverSocket.register(selector, SelectionKey.OP_ACCEPT);
24 | ByteBuffer buffer = ByteBuffer.allocate(256);
25 |
26 | while (true) {
27 | System.out.println("Waiting for request...");
28 | selector.select();
29 | Set selectedKeys = selector.selectedKeys();
30 | Iterator iter = selectedKeys.iterator();
31 | while (iter.hasNext()) {
32 |
33 | SelectionKey key = iter.next();
34 |
35 | if (key.isAcceptable()) {
36 | register(selector, serverSocket);
37 | }
38 |
39 | if (key.isReadable()) {
40 | answerWithEcho(buffer, key);
41 | }
42 | iter.remove();
43 | }
44 | }
45 | }
46 |
47 | private static void answerWithEcho(ByteBuffer buffer, SelectionKey key) throws IOException {
48 | SocketChannel client = (SocketChannel) key.channel();
49 | int r = client.read(buffer);
50 | if (r == -1 || new String(buffer.array()).trim()
51 | .equals(POISON_PILL)) {
52 | client.close();
53 | System.out.println("Not accepting client messages anymore");
54 | } else {
55 | buffer.flip();
56 | client.write(buffer);
57 | buffer.clear();
58 | }
59 | }
60 |
61 | private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException {
62 | SocketChannel client = serverSocket.accept();
63 | client.configureBlocking(false);
64 | client.register(selector, SelectionKey.OP_READ);
65 | }
66 |
67 | public static Process start() throws IOException, InterruptedException {
68 | String javaHome = System.getProperty("java.home");
69 | String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
70 | String classpath = System.getProperty("java.class.path");
71 | String className = EchoServer.class.getCanonicalName();
72 |
73 | ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
74 |
75 | return builder.start();
76 | }
77 | }
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/udp/filestreamer/MulticastClient.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.udp.filestreamer;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/socketJ.zip
3 | // MulticastClient.java
4 |
5 | import java.io.*;
6 | import java.net.*;
7 | import java.util.*;
8 |
9 | public class MulticastClient {
10 |
11 | public static void main(String[] args) {
12 |
13 | // creazione della socket multicast
14 | MulticastSocket socket=null;
15 | try{
16 | socket = new MulticastSocket(MulticastServer.PORT);
17 | socket.setSoTimeout(20000); // 20 secondi
18 | System.out.println("\nMulticastClient: avviato");
19 | System.out.println("Creata la socket: "+ socket);
20 | }
21 | catch (IOException e) {
22 | System.out.println("Problemi nella creazione della socket: ");
23 | e.printStackTrace();
24 | System.exit(1);
25 | }
26 |
27 | // adesione al gruppo associato all'indirizzo multicast
28 | InetAddress address=null;
29 | try{
30 | address = InetAddress.getByName("231.0.0.1");
31 | socket.joinGroup(address);
32 | System.out.println("Adesione al gruppo "+ address);
33 | }
34 | catch (IOException e) {
35 | System.out.println("Problemi nell'adesione al gruppo: ");
36 | e.printStackTrace();
37 | System.exit(2);
38 | }
39 |
40 | DatagramPacket packet;
41 |
42 | // ricezione di alcune linee
43 | for (int i = 0; i < 100; i++) {
44 | System.out.println("\nIn attesa di un datagramma... ");
45 |
46 | byte[] buf = new byte[256];
47 | packet = new DatagramPacket(buf, buf.length);
48 | try{
49 | socket.receive(packet);
50 | }
51 | catch (IOException e) {
52 | System.out.println("Problemi nella ricezione del datagramma: ");
53 | e.printStackTrace();
54 | continue;
55 | // anche se ci sono problemi riprende il ciclo di ricezioni
56 | }
57 | try{
58 | String linea=null;
59 | linea = DatagramUtility.getContent(packet);
60 | System.out.println("Linea ricevuta: " + linea);
61 | }
62 | catch (IOException e) {
63 | System.out.println("Problemi nella lettura del datagramma: ");
64 | e.printStackTrace();
65 | continue;
66 | // anche se ci sono problemi riprende il ciclo di ricezioni
67 | }
68 | } //for
69 | // uscita dal gruppo e chiusura della socket
70 | System.out.println("\nUscita dal gruppo");
71 | try{
72 | socket.leaveGroup(address);
73 | }
74 | catch (IOException e) {
75 | System.out.println("Problemi nell'uscita dal gruppo: ");
76 | e.printStackTrace();
77 | }
78 | System.out.println("MulticastClient: termino...");
79 | socket.close();
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/goosegame/Player.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.goosegame;
2 |
3 | public class Player extends Thread {
4 | int position = 0;
5 | int index; // Index of the Thread
6 | Game game; // Game
7 |
8 | Player(int index, Game game) {
9 | this.index = index;
10 | this.game = game;
11 | }
12 |
13 | @Override
14 | public void run() {
15 | int roundNumber;
16 | // Loop
17 | while (true) {
18 | roundNumber = game.getRound(); // Gets the Round Number
19 |
20 | if (roundNumber == -1) { // Lost
21 | space();
22 | System.out.println("[" + index + "] " + "Oh no, I've lost :(");
23 | break;
24 | } else if (roundNumber == index) { // It's my turn
25 | space();
26 | System.out.println("[" + index + "] " + "Play - Current Score:" + position);
27 | position += rollDice();
28 | if (position > 100) {
29 | space();
30 | System.out.println("[" + index + "] " + "Yeah I won :) I got more than 100, my score is:" + position);
31 | game.setRound(-1);
32 | break;
33 | } else { // Pass
34 | space();
35 | System.out.println("[" + index + "] " + " Not enough, Pass. My current Score is:" + position);
36 | game.setRound(1 - index);
37 | // Notify
38 | try {
39 | game.gameNotify();
40 | } catch (InterruptedException e) {
41 | e.printStackTrace();
42 | }
43 | // Go to sleep
44 | try {
45 | game.sleep();
46 | } catch (InterruptedException e) {
47 | e.printStackTrace();
48 | }
49 | }
50 | } else { // Not my turn
51 | // Notify
52 | try {
53 | game.gameNotify();
54 | } catch (InterruptedException e) {
55 | e.printStackTrace();
56 | }
57 | try {
58 | space();
59 | System.out.println("[" + index + "]" + "Not my turn");
60 | game.gameWait();
61 | } catch (InterruptedException e) {
62 | e.printStackTrace();
63 | }
64 | }
65 | }
66 | space();
67 | System.out.println("[" + index + "] " + "I'm done");
68 | // Notify the other
69 | try {
70 | game.gameNotify();
71 | } catch (InterruptedException e) {
72 | e.printStackTrace();
73 | }
74 | }
75 |
76 | int rollDice() {
77 | int dice = (int) (Math.random() * 10 + 1);
78 | space();
79 | System.out.println("\uD83C\uDFB2 extracted:" + dice);
80 | return (dice);
81 | }
82 |
83 | void space() {
84 | if (index == 1) {
85 | System.out.print(" ");
86 | }
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/dicegame/Player.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.dicegame;
2 |
3 |
4 | public class Player extends Thread {
5 |
6 | int wallet;
7 | int budget;
8 | String name;
9 | Banco banco;
10 | int matchPlayed;
11 |
12 | Player(String name, int wallet, Banco banco) {
13 | this.wallet = wallet;
14 | this.budget = wallet;
15 | this.name = name;
16 | this.banco = banco;
17 | this.matchPlayed=0;
18 | }
19 |
20 | @Override
21 | public void run() {
22 | banco.increaseNumPlayers();
23 | while (true) {
24 | System.out.println("["+name+"] would like to play, checking games availability...");
25 | if (banco.getMatchesCounter()==0) {
26 | System.out.println("["+name+"] no more games available! Bye!");
27 | break; // If there are no more matches, stop playing
28 | }
29 | banco.decreaseMatchCounters(); // Decrease match counter
30 | this.matchPlayed++; // Increase coin
31 | System.out.println("["+name+"] playing my "+matchPlayed+" match, there are ... "+banco.getMatchesCounter()+" matches left");
32 |
33 | int dice=rollDice(); // Roll Dice
34 | printStatus(); // Print Status
35 | int potentialOutcome=outcome(dice); // Calculate Outcome
36 | System.out.println("["+name+"] Potential outcome: "+potentialOutcome);
37 | wallet+=(potentialOutcome<0) ? pay(potentialOutcome) : banco.getMoney(name,potentialOutcome); // Pay or Get
38 | printStatus(); // Print Status
39 | if (wallet==0) {
40 | System.out.println("["+name+"] has no money left!");
41 | break; // If wallet is empty, stop playing
42 | }
43 | if (banco.getJackpot()>=3) { // If there are at least 3 coins in the jackpot
44 | banco.resumeOtherGames(); // Resume other games
45 | }
46 |
47 | }
48 | banco.decreaseNumPlayers();
49 | }
50 |
51 | int pay(int outcome) {
52 | int newWallet = wallet + outcome;
53 | if (newWallet <= 0) {
54 | System.out.println("["+name+"] has only " + wallet + " and have to pay " + outcome + "!");
55 | this.banco.addToJackpot(wallet);
56 | return -wallet; // I can pay only what I have
57 | } else {
58 | this.banco.addToJackpot(-outcome);
59 | }
60 | return outcome;
61 | }
62 |
63 | int rollDice() {
64 | int dice = (int) (Math.random() * 6 + 1);
65 | System.out.println("["+name+"] \uD83C\uDFB2:" + dice);
66 | return (dice);
67 | }
68 |
69 | int outcome(int dice){
70 | int outcome = 0;
71 | switch (dice) {
72 | case 1:
73 | outcome = -2; // Pay 2
74 | break;
75 | case 2:
76 | outcome = -1; // Pay 1
77 | break;
78 | case 4:
79 | outcome = 1; // Get 1
80 | break;
81 | case 5:
82 | outcome = 2; // Get 2
83 | break;
84 | case 6:
85 | outcome = 3; // Get 3
86 | break;
87 | }
88 | return outcome;
89 | }
90 |
91 | void printStatus() {
92 | System.out.println("["+name+"] Matches "+ matchPlayed+" Wallet \uD83D\uDC5B " + wallet + " Initial: "+budget+" Jackpot \uD83C\uDFB0 " + banco.getJackpot() + " Num players playing:"+banco.getNumPlayers());
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/thread/soccergame/Team.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.thread.soccergame;
2 |
3 | public class Team extends Thread {
4 | int position = 0;
5 | int index; // Index of the Thread
6 | Game game; // Game
7 | int goal=0;
8 |
9 | public int getGoal() {
10 | return goal;
11 | }
12 |
13 | private String teamName; // Name of the team
14 |
15 | public String getTeamName() {
16 | return teamName;
17 | }
18 |
19 |
20 | Team(int index, String teamName,Game game) {
21 | this.index = index;
22 | this.teamName=teamName;
23 | this.game = game;
24 | }
25 |
26 |
27 | @Override
28 | public void run() {
29 | int roundNumber;
30 | int time;
31 | int dice;
32 | int partial=0; // Variable to keep track of the number of consecutive "Keep Ball"
33 |
34 | while ((time=game.getTime()) <= 90) { // Main loop
35 | roundNumber=game.getRound();
36 | if (roundNumber == index) {
37 | System.out.println("Team "+teamName+" plays");
38 | System.out.println("🕑 ["+time+ "]");
39 | game.addTime(); // New Minute, incremented only by the thread of team that plays
40 | dice=rollDice(); // Roll the dice
41 | switch (dice) {
42 | case 1: // Goal
43 | System.out.println("⚽⚽⚽ GOAL ⚽⚽⚽");
44 | partial=0;
45 | goal++;
46 | sleepAndNotify();
47 | break;
48 | case 2: // Loss Ball
49 | System.out.println("↔ Loss Ball");
50 | partial=0;
51 | sleepAndNotify();
52 | break;
53 | case 3: // Keep Ball
54 | System.out.println("Keep Ball");
55 | partial += 1;
56 | if (partial >=3 ) {
57 | System.out.println("⏳ Keep Ball Timeout");
58 | sleepAndNotify();
59 | }
60 | break;
61 |
62 | default:
63 | break;
64 | }
65 |
66 | } else {
67 | // Notify
68 | try {
69 | game.gameNotify();
70 | } catch (InterruptedException e) {
71 | e.printStackTrace();
72 | }
73 | try {
74 | //System.out.println("Team "+teamName+" waits");
75 | game.gameWait();
76 | } catch (InterruptedException e) {
77 | e.printStackTrace();
78 | }
79 | }
80 |
81 |
82 | }
83 | try {
84 | game.gameNotify();
85 | } catch (InterruptedException e) {
86 | e.printStackTrace();
87 | }
88 | }
89 |
90 | int rollDice() {
91 | int dice = (int) (Math.random() * 3 + 1);
92 | System.out.println("\uD83C\uDFB2 extracted:" + dice);
93 | return (dice);
94 | }
95 |
96 | void sleepAndNotify(){
97 | game.setRound(1 - index);
98 | // Notify
99 | try {
100 | game.gameNotify();
101 | } catch (InterruptedException e) {
102 | e.printStackTrace();
103 | }
104 | // Go to sleep
105 | try {
106 | game.sleep();
107 | } catch (InterruptedException e) {
108 | e.printStackTrace();
109 | }
110 | }
111 |
112 | }
113 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/udp/filestreamer/MulticastServer.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.udp.filestreamer;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/socketJ.zip
3 | // MulticastServer.java
4 |
5 | import java.io.*;
6 | import java.net.*;
7 |
8 | public class MulticastServer {
9 |
10 | public static final int PORT = 4446;
11 | // porta al di fuori del range 1-1024 !
12 | // dichiarata come statica perchè caratterizza il server
13 |
14 | public static final String FILE = "resources/dante.txt";
15 | static BufferedReader in = null;
16 | static boolean moreLines = true;
17 |
18 | public static void main(String[] args) {
19 | long WAIT = 1000;
20 | int count=0;
21 | MulticastSocket socket = null;
22 | String currentPath = null;
23 | try {
24 | currentPath = new File(".").getCanonicalPath();
25 | } catch (IOException e) {
26 | e.printStackTrace();
27 | }
28 | System.out.println("Current dir:" + currentPath);
29 |
30 | String currentDir = System.getProperty("user.dir");
31 | System.out.println("Current dir using System:" + currentDir);
32 |
33 | System.out.println("MulticastServer: avviato");
34 |
35 | // creazione della socket datagram
36 | try {
37 | socket = new MulticastSocket(PORT);
38 | System.out.println("Socket: " + socket);
39 | }
40 | catch (IOException e) {
41 | System.out.println("Problemi nella creazione della socket: ");
42 | e.printStackTrace();
43 | System.exit(1);
44 | }
45 | // associazione di uno stream di input al file da cui estrarre le linee
46 | try {
47 | in = new BufferedReader(new FileReader(FILE));
48 | System.out.println("File "+FILE+" aperto");
49 | }
50 | catch (FileNotFoundException e) {
51 | System.out.println("Problemi nell'apertura del file: ");
52 | e.printStackTrace();
53 | System.exit(2);
54 | }
55 | // creazione del gruppo associato all'indirizzo multicast
56 | InetAddress group=null;
57 | try{
58 | group = InetAddress.getByName("231.0.0.1");
59 | socket.joinGroup(group);
60 | System.out.println("Creazione del gruppo "+ group);
61 | }
62 | catch (IOException e) {
63 | System.out.println("Problemi nella creazione del gruppo: ");
64 | e.printStackTrace();
65 | System.exit(3);
66 | }
67 |
68 | while (moreLines) {
69 | count++;
70 | byte[] buf = new byte[256];
71 | // estrazione della linea
72 | String linea = LineUtility.getNextLine(in);
73 | if (linea.equals("Nessuna linea disponibile"))
74 | moreLines = false;
75 | System.out.println("Estratta linea # "+count+" : "+linea);
76 |
77 | // costruzione del datagramma contenente la linea
78 | try {
79 | DatagramPacket packet = DatagramUtility.buildPacket(group, PORT, linea);
80 | // invio della linea al gruppo
81 | socket.send(packet);
82 | System.out.println("Linea inviata");
83 | }
84 | catch (Exception e) {
85 | System.out.println("Problemi nell'invio del datagramma: ");
86 | e.printStackTrace();
87 | continue;
88 | }
89 |
90 | // attesa tra un invio e l'altro...
91 | try {
92 | Thread.sleep((long)(Math.random() * WAIT));
93 | } catch (InterruptedException e) { }
94 | } // while
95 | System.out.println("File terminato");
96 | System.out.println("MulticastServer: termino...");
97 | socket.close();
98 | }
99 | }
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/udp/filestreamer/LineServer.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.udp.filestreamer;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/socketJ.zip
3 | // LineServer.java
4 |
5 | import java.io.*;
6 | import java.net.*;
7 | import java.util.*;
8 |
9 | public class LineServer {
10 |
11 | public static final int PORT = 4445;
12 | // porta al di fuori del range 1-1024
13 |
14 | public static void main(String[] args) {
15 | System.out.println("LineServer: avviato");
16 | DatagramSocket socket = null;
17 | try {
18 | // creazione della socket datagram
19 | socket = new DatagramSocket(PORT);
20 | System.out.println("Creata la socket: " + socket);
21 | }
22 | catch (SocketException e) {
23 | System.out.println("Problemi nella creazione della socket: ");
24 | e.printStackTrace();
25 | System.exit(1);
26 | }
27 | try{
28 | while (true) {
29 | System.out.println("\nIn attesa di richieste...");
30 | // ricezione del datagramma
31 | DatagramPacket packet=null;
32 | InetAddress mittAddr=null;
33 | int mittPort=0;
34 | try{
35 | byte[] buf = new byte[256];
36 | packet = new DatagramPacket(buf, buf.length);
37 | socket.receive(packet);
38 | mittAddr = packet.getAddress();
39 | mittPort = packet.getPort();
40 | System.out.println("Ricevuta richiesta da "+mittAddr+", "+mittPort);
41 | }
42 | catch(IOException e){
43 | System.err.println("Problemi nella ricezione del datagramma: " + e.getMessage());
44 | e.printStackTrace();
45 | continue;
46 | // il server continua a fornire il servizio ricominciando dall'inizio del ciclo
47 | }
48 | // lettura della richiesta
49 | String nomeFile;
50 | int numLinea;
51 | try{
52 | String richiesta = DatagramUtility.getContent(packet);
53 | StringTokenizer st = new StringTokenizer(richiesta);
54 | nomeFile = st.nextToken();
55 | numLinea = Integer.parseInt(st.nextToken());
56 | System.out.println("Richiesta linea "+numLinea+" del file "+nomeFile);
57 | }
58 | catch(Exception e){
59 | System.err.println("Problemi nella lettura della richiesta: " + e.getMessage());
60 | e.printStackTrace();
61 | continue;
62 | // il server continua a fornire il servizio ricominciando dall'inizio del ciclo
63 | }
64 | // preparazione della linea e invio della risposta
65 | try{
66 | String linea = LineUtility.getLine(nomeFile, numLinea);
67 | byte[] data = new byte[256];
68 | data = linea.getBytes();
69 | packet = new DatagramPacket(data, data.length, mittAddr, mittPort);
70 | socket.send(packet);
71 | System.out.println("Risposta inviata a "+mittAddr+", "+mittPort);
72 | }
73 | catch(IOException e){
74 | System.err.println("Problemi nell'invio della risposta: " + e.getMessage());
75 | e.printStackTrace();
76 | continue;
77 | // il server continua a fornire il servizio ricominciando dall'inizio del ciclo
78 | }
79 | } // while
80 | }
81 | // qui catturo le eccezioni non catturate all'interno del while
82 | // in seguito alle quali il server termina l'esecuzione
83 | catch(Exception e){
84 | e.printStackTrace();
85 | }
86 | System.out.println("LineServer: termino...");
87 | socket.close();
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/src/main/java/edu/unict/tswd/socket/udp/filestreamer/LineClient.java:
--------------------------------------------------------------------------------
1 | package edu.unict.tswd.socket.udp.filestreamer;
2 | // Inspired by www.dmi.unict.it/tramonta/lessons/sd/socketJ.zip
3 | // LineClient.java
4 |
5 | import java.io.*;
6 | import java.net.*;
7 | import java.util.*;
8 |
9 | public class LineClient {
10 |
11 | public static final int PORT = 4445;
12 | // porta al di fuori del range 1-1024
13 |
14 | public static void main(String[] args) {
15 |
16 | DatagramSocket socket=null;
17 |
18 | // creazione della socket datagram con un timeout di 30s
19 | try{
20 | socket = new DatagramSocket();
21 | socket.setSoTimeout(30000);
22 | System.out.println("\nLineClient: avviato");
23 | System.out.println("Creata la socket: "+ socket);
24 | }
25 | catch (SocketException e) {
26 | System.out.println("Problemi nella creazione della socket: ");
27 | e.printStackTrace();
28 | System.out.println("LineClient: interrompo...");
29 | System.exit(1);
30 | }
31 |
32 | InetAddress addr=null;
33 |
34 | try{
35 | if (args.length == 0) addr = InetAddress.getByName(null);
36 | else addr = InetAddress.getByName(args[0]);
37 | }
38 | catch(UnknownHostException e){
39 | System.out.println("Problemi nel determinare l'indirizzo del server: ");
40 | e.printStackTrace();
41 | System.out.println("LineClient: interrompo...");
42 | System.exit(2);
43 | }
44 |
45 | BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
46 | String richiesta=null;
47 | System.out.print("\n^D(Unix)/^Z(Win) per uscire, invio per continuare: ");
48 |
49 | try{
50 | while (stdIn.readLine()!=null){
51 | try{
52 | System.out.print("Nome del file (con estensione)? ");
53 | String nomeFile = stdIn.readLine();
54 | System.out.print("Numero della linea? ");
55 | int numLinea = Integer.parseInt(stdIn.readLine());
56 | richiesta = nomeFile+" "+numLinea;
57 | }
58 | catch (Exception e) {
59 | System.out.println("Problemi nell'interazione da console: ");
60 | e.printStackTrace();
61 | System.out.print("\n^D(Unix)/^Z(Win) per uscire, invio per continuare: ");
62 | continue;
63 | // il client continua l'esecuzione riprendendo dall'inizio del ciclo
64 | }
65 |
66 | // creazione e invio del pacchetto
67 | try{
68 | DatagramPacket packetOUT = DatagramUtility.buildPacket(addr, PORT, richiesta);
69 | socket.send(packetOUT);
70 | System.out.println("Richiesta inviata a "+addr+", "+PORT);
71 | }
72 | catch (IOException e) {
73 | System.out.println("Problemi nell'invio della richiesta: ");
74 | e.printStackTrace();
75 | System.out.print("\n^D(Unix)/^Z(Win) per uscire, invio per continuare: ");
76 | continue;
77 | }
78 |
79 | // ricezione e stampa della risposta
80 | DatagramPacket packetIN=null;
81 | try{
82 | byte[] buf = new byte[256];
83 | packetIN = new DatagramPacket(buf, buf.length);
84 | socket.receive(packetIN);
85 | // bloccante solo per i millisecondi indicati, dopo solleva una eccezione
86 | }
87 | catch (IOException e) {
88 | System.out.println("Problemi nella ricezione del datagramma: ");
89 | e.printStackTrace();
90 | System.out.print("\n^D(Unix)/^Z(Win) per uscire, invio per continuare: ");
91 | continue;
92 | // il client continua l'esecuzione riprendendo dall'inizio del ciclo
93 | }
94 |
95 | String risposta = new String(packetIN.getData());
96 | System.out.println("Risposta: " + risposta);
97 |
98 | // tutto ok, pronto per nuova richiesta
99 | System.out.print("\n^D(Unix)/^Z(Win) per uscire, invio per continuare: ");
100 | } // while
101 | }
102 | // qui catturo le eccezioni non catturate all'interno del while
103 | // in seguito alle quali il client termina l'esecuzione
104 | catch(Exception e){
105 | e.printStackTrace();
106 | }
107 |
108 | System.out.println("LineClient: termino...");
109 | socket.close();
110 | }
111 | }
112 |
--------------------------------------------------------------------------------