This repository was archived by the owner on Oct 19, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerMultithread.java
More file actions
75 lines (56 loc) · 2.13 KB
/
ServerMultithread.java
File metadata and controls
75 lines (56 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// SERVER MULTITHREAD TCP
import java.io.*;
import java.net.*;
public class ServerMultithread {
public static void main(String[] args) {
final int PORT = 3000;
final ServerSocket server;
// creazione server
try {
server = new ServerSocket(PORT);
System.out.println("Creato server: " + server.getInetAddress() + " porta " + server.getLocalPort());
} catch (IOException e) {
System.out.println("Errore creazione server");
return;
}
// accettazione client: spawn thread per ognuno
int idThread = 0;
while (true) {
try {
Socket client = server.accept();
Thread thread = new Server(client, idThread);
thread.start();
System.out.println("Lanciato Thread-" + idThread + " con client (" + client.getInetAddress() + " porta " + client.getPort() + ")");
idThread++;
} catch (IOException e) {
System.out.println("Errore connessione client, ignoro");
}
}
}
}
class Server extends Thread {
private Socket client;
private final int id;
public Server(Socket client, int id) {
this.client = client;
this.id = id;
}
public void run() {
byte[] buffer = new byte[1000];
// scambio di messaggi (senza logica di uscita, aggiungerla in base alla storiella)
while (true) {
try {
int size = client.getInputStream().read(buffer);
String msg = new String(buffer, 0, size);
System.out.println("Thread-" + id + ": Ricevuto da (" + client.getInetAddress() + " porta " + client.getPort() + "):\n" + msg);
String res = "ACK";
client.getOutputStream().write(res.getBytes());
} catch (IOException e) {
System.out.println("Thread-" + id + ": Errore nella comunicazione, ignoro");
} catch (Exception e) {
System.out.println("Thread-" + id + ": Errore grave, chiudo");
return;
}
}
}
}