-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimScaleSics.java
More file actions
581 lines (497 loc) · 23.6 KB
/
Copy pathSimScaleSics.java
File metadata and controls
581 lines (497 loc) · 23.6 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
public class SimScaleSics extends JFrame {
private double currentGrossWeight = 0.00;
private double tareWeight = 0.00;
private double maxCapacity = 5000.0;
private int decimalPlaces = 2;
private String uom = "g";
private boolean isStable = true;
private boolean isOverload = false;
private boolean updatingControls = false;
private boolean isCompactMode = false;
// Componenti UI
private JPanel advancedPanel;
private JButton btnToggleView;
private JLabel lblDisplayWeight;
private JLabel lblDisplayUom;
private JLabel lblStatusFlag;
private JLabel lblSubInfo;
private JSpinner spGrossWeight;
private JSlider slGrossWeight;
private JComboBox<Integer> cbDecimals;
private JComboBox<String> cbUom;
private JTextField txtMaxCapacity;
private JCheckBox chkStable;
private JCheckBox chkOverload;
private JTextArea txtLog;
private JButton btnStartStop;
private JTextField txtBindIp;
private JTextField txtPort;
// Networking
private ServerSocket serverSocket;
private Thread serverThread;
private volatile boolean isRunning = false;
public SimScaleSics() {
setTitle("CONSALVO & G. - SimScaleSics Terminal");
setSize(820, 840);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
initUI();
startServer();
}
private void initUI() {
JPanel mainPanel = new JPanel(new BorderLayout(8, 8));
mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
// ==========================================
// 1. TERMINALE BILANCIA (Frontalino Hardware)
// ==========================================
JPanel chassisPanel = new JPanel(new BorderLayout(4, 6));
chassisPanel.setBackground(new Color(38, 42, 48));
chassisPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(60, 65, 70), 2),
new EmptyBorder(8, 12, 8, 12)
));
// Cornice Superiore: Brand, Modello e Pulsante About [?]
JPanel brandBar = new JPanel(new BorderLayout(8, 0));
brandBar.setOpaque(false);
JLabel lblBrand = new JLabel("CONSALVO & G.");
lblBrand.setFont(new Font("SansSerif", Font.BOLD, 13));
lblBrand.setForeground(new Color(220, 220, 220));
JPanel brandRightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 0));
brandRightPanel.setOpaque(false);
JLabel lblModel = new JLabel("SIMSCALESICS | MOD. CG-SICS");
lblModel.setFont(new Font("Monospaced", Font.PLAIN, 10));
lblModel.setForeground(new Color(150, 155, 160));
JButton btnAbout = new JButton("?");
btnAbout.setFont(new Font("SansSerif", Font.BOLD, 11));
btnAbout.setMargin(new Insets(1, 7, 1, 7));
btnAbout.setFocusPainted(false);
btnAbout.setBackground(new Color(55, 60, 68));
btnAbout.setForeground(Color.WHITE);
btnAbout.setToolTipText("Informazioni e Contatti");
btnAbout.addActionListener(e -> showAboutDialog());
brandRightPanel.add(lblModel);
brandRightPanel.add(btnAbout);
brandBar.add(lblBrand, BorderLayout.WEST);
brandBar.add(brandRightPanel, BorderLayout.EAST);
chassisPanel.add(brandBar, BorderLayout.NORTH);
// Display LCD Retroilluminato
JPanel displayPanel = new JPanel(new BorderLayout());
displayPanel.setBackground(new Color(18, 24, 20));
displayPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(10, 15, 12), 2),
new EmptyBorder(8, 14, 8, 14)
));
JPanel headerDisplay = new JPanel(new BorderLayout());
headerDisplay.setOpaque(false);
lblStatusFlag = new JLabel("[ GROSS | STABLE ]");
lblStatusFlag.setFont(new Font("Monospaced", Font.BOLD, 12));
lblStatusFlag.setForeground(new Color(50, 205, 50));
headerDisplay.add(lblStatusFlag, BorderLayout.WEST);
lblSubInfo = new JLabel("G: 0.00 g | T: 0.00 g");
lblSubInfo.setFont(new Font("Monospaced", Font.PLAIN, 11));
lblSubInfo.setForeground(new Color(140, 190, 150));
headerDisplay.add(lblSubInfo, BorderLayout.EAST);
displayPanel.add(headerDisplay, BorderLayout.NORTH);
lblDisplayWeight = new JLabel("0.00", SwingConstants.RIGHT);
lblDisplayWeight.setFont(new Font("Monospaced", Font.BOLD, 46));
lblDisplayWeight.setForeground(new Color(0, 255, 128));
lblDisplayUom = new JLabel(" g", SwingConstants.LEFT);
lblDisplayUom.setFont(new Font("Monospaced", Font.BOLD, 24));
lblDisplayUom.setForeground(new Color(0, 255, 128));
JPanel weightRow = new JPanel(new BorderLayout(8, 0));
weightRow.setOpaque(false);
weightRow.add(lblDisplayWeight, BorderLayout.CENTER);
weightRow.add(lblDisplayUom, BorderLayout.EAST);
displayPanel.add(weightRow, BorderLayout.CENTER);
chassisPanel.add(displayPanel, BorderLayout.CENTER);
// Barra Carico Rapido
JPanel quickLoadPanel = new JPanel(new BorderLayout(8, 0));
quickLoadPanel.setOpaque(false);
quickLoadPanel.setBorder(new EmptyBorder(6, 0, 4, 0));
JLabel lblQuickLoad = new JLabel("Carico: ");
lblQuickLoad.setFont(new Font("SansSerif", Font.BOLD, 11));
lblQuickLoad.setForeground(Color.LIGHT_GRAY);
quickLoadPanel.add(lblQuickLoad, BorderLayout.WEST);
slGrossWeight = new JSlider(0, (int) (maxCapacity * Math.pow(10, decimalPlaces)), 0);
slGrossWeight.setBackground(new Color(38, 42, 48));
slGrossWeight.addChangeListener(e -> {
if (updatingControls) return;
double factor = Math.pow(10, decimalPlaces);
currentGrossWeight = slGrossWeight.getValue() / factor;
updatingControls = true;
spGrossWeight.setValue(currentGrossWeight);
updatingControls = false;
refreshDisplay();
});
quickLoadPanel.add(slGrossWeight, BorderLayout.CENTER);
spGrossWeight = new JSpinner(new SpinnerNumberModel(0.0, 0.0, 500000.0, 0.00001));
spGrossWeight.setPreferredSize(new Dimension(100, 24));
spGrossWeight.addChangeListener(e -> {
if (updatingControls) return;
currentGrossWeight = ((Number) spGrossWeight.getValue()).doubleValue();
syncSliderWithWeight();
refreshDisplay();
});
quickLoadPanel.add(spGrossWeight, BorderLayout.EAST);
// Barra Tasti Funzione & Toggle Compatto
JPanel keypadPanel = new JPanel(new BorderLayout());
keypadPanel.setOpaque(false);
JPanel functionKeys = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 4));
functionKeys.setOpaque(false);
JButton btnZero = new JButton("-> 0 <- ZERO");
btnZero.setFont(new Font("SansSerif", Font.BOLD, 11));
btnZero.setBackground(new Color(55, 60, 68));
btnZero.setForeground(Color.WHITE);
btnZero.setFocusPainted(false);
btnZero.addActionListener(e -> executeZero());
JButton btnTare = new JButton("-> T <- TARA");
btnTare.setFont(new Font("SansSerif", Font.BOLD, 11));
btnTare.setBackground(new Color(55, 60, 68));
btnTare.setForeground(Color.WHITE);
btnTare.setFocusPainted(false);
btnTare.addActionListener(e -> executeTare());
JButton btnClearTare = new JButton("TAC CANC.");
btnClearTare.setFont(new Font("SansSerif", Font.BOLD, 11));
btnClearTare.setBackground(new Color(55, 60, 68));
btnClearTare.setForeground(Color.WHITE);
btnClearTare.setFocusPainted(false);
btnClearTare.addActionListener(e -> executeClearTare());
functionKeys.add(btnZero);
functionKeys.add(btnTare);
functionKeys.add(btnClearTare);
btnToggleView = new JButton("Vista Compatta [-]");
btnToggleView.setFont(new Font("SansSerif", Font.PLAIN, 11));
btnToggleView.setFocusPainted(false);
btnToggleView.addActionListener(e -> toggleViewMode());
keypadPanel.add(functionKeys, BorderLayout.CENTER);
keypadPanel.add(btnToggleView, BorderLayout.EAST);
JPanel terminalControls = new JPanel(new BorderLayout());
terminalControls.setOpaque(false);
terminalControls.add(quickLoadPanel, BorderLayout.NORTH);
terminalControls.add(keypadPanel, BorderLayout.SOUTH);
chassisPanel.add(terminalControls, BorderLayout.SOUTH);
mainPanel.add(chassisPanel, BorderLayout.NORTH);
// ==========================================
// 2. PANNELLO AVANZATO (Configurazione + Debug)
// ==========================================
advancedPanel = new JPanel();
advancedPanel.setLayout(new BoxLayout(advancedPanel, BoxLayout.Y_AXIS));
// Rete TCP
JPanel netPanel = new JPanel(new GridBagLayout());
netPanel.setBorder(BorderFactory.createTitledBorder("Configurazione Rete TCP"));
GridBagConstraints gbcNet = new GridBagConstraints();
gbcNet.insets = new Insets(4, 6, 4, 6);
gbcNet.fill = GridBagConstraints.HORIZONTAL;
gbcNet.gridx = 0; gbcNet.gridy = 0;
netPanel.add(new JLabel("Bind IP:"), gbcNet);
gbcNet.gridx = 1; gbcNet.gridy = 0; gbcNet.weightx = 1.0;
txtBindIp = new JTextField("0.0.0.0");
netPanel.add(txtBindIp, gbcNet);
gbcNet.gridx = 2; gbcNet.gridy = 0; gbcNet.weightx = 0;
netPanel.add(new JLabel("Porta:"), gbcNet);
gbcNet.gridx = 3; gbcNet.gridy = 0; gbcNet.weightx = 0.5;
txtPort = new JTextField("4001");
netPanel.add(txtPort, gbcNet);
gbcNet.gridx = 4; gbcNet.gridy = 0; gbcNet.weightx = 0;
btnStartStop = new JButton("Riavvia Server");
btnStartStop.addActionListener(e -> restartServer());
netPanel.add(btnStartStop, gbcNet);
advancedPanel.add(netPanel);
// Parametri Metrologici
JPanel controlPanel = new JPanel(new GridBagLayout());
controlPanel.setBorder(BorderFactory.createTitledBorder("Parametri Metrologici"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 8, 5, 8);
gbc.fill = GridBagConstraints.HORIZONTAL;
// Riga 1: Decimali (0..5) e Unità
gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 0.0;
controlPanel.add(new JLabel("Decimali:"), gbc);
gbc.gridx = 1; gbc.gridy = 0; gbc.weightx = 0.5;
cbDecimals = new JComboBox<>(new Integer[]{0, 1, 2, 3, 4, 5});
cbDecimals.setSelectedItem(2);
cbDecimals.addActionListener(e -> {
decimalPlaces = (int) cbDecimals.getSelectedItem();
updateSliderBounds();
refreshDisplay();
});
controlPanel.add(cbDecimals, gbc);
gbc.gridx = 2; gbc.gridy = 0; gbc.weightx = 0.0;
controlPanel.add(new JLabel("Unita (UoM):"), gbc);
gbc.gridx = 3; gbc.gridy = 0; gbc.weightx = 0.5;
cbUom = new JComboBox<>(new String[]{"g", "kg", "mg", "lb"});
cbUom.setSelectedItem("g");
cbUom.addActionListener(e -> {
uom = (String) cbUom.getSelectedItem();
lblDisplayUom.setText(" " + uom);
refreshDisplay();
});
controlPanel.add(cbUom, gbc);
// Riga 2: Portata Max e Checkbox di stato
gbc.gridx = 0; gbc.gridy = 1; gbc.weightx = 0.0;
controlPanel.add(new JLabel("Portata Max:"), gbc);
gbc.gridx = 1; gbc.gridy = 1; gbc.weightx = 0.5;
txtMaxCapacity = new JTextField("5000.0");
txtMaxCapacity.setPreferredSize(new Dimension(90, 24));
txtMaxCapacity.addActionListener(e -> {
try {
maxCapacity = Double.parseDouble(txtMaxCapacity.getText());
updateSliderBounds();
} catch (NumberFormatException ignored) {}
});
controlPanel.add(txtMaxCapacity, gbc);
gbc.gridx = 2; gbc.gridy = 1; gbc.weightx = 0.0;
chkStable = new JCheckBox("Stato Stabile", true);
chkStable.addActionListener(e -> {
isStable = chkStable.isSelected();
refreshDisplay();
});
controlPanel.add(chkStable, gbc);
gbc.gridx = 3; gbc.gridy = 1; gbc.weightx = 0.5;
chkOverload = new JCheckBox("Sovraccarico (+)", false);
chkOverload.addActionListener(e -> {
isOverload = chkOverload.isSelected();
refreshDisplay();
});
controlPanel.add(chkOverload, gbc);
advancedPanel.add(controlPanel);
// Log Comunicazione
JPanel logPanel = new JPanel(new BorderLayout(4, 4));
logPanel.setBorder(BorderFactory.createTitledBorder("Log Comunicazione SICS / MMR"));
txtLog = new JTextArea(8, 50);
txtLog.setFont(new Font("Monospaced", Font.PLAIN, 12));
txtLog.setEditable(false);
logPanel.add(new JScrollPane(txtLog), BorderLayout.CENTER);
JLabel lblFooter = new JLabel("SimScaleSics | Antonello Consalvo & G.", SwingConstants.RIGHT);
lblFooter.setFont(new Font("SansSerif", Font.ITALIC, 11));
lblFooter.setForeground(new Color(120, 120, 120));
logPanel.add(lblFooter, BorderLayout.SOUTH);
advancedPanel.add(logPanel);
mainPanel.add(advancedPanel, BorderLayout.CENTER);
add(mainPanel);
}
private void showAboutDialog() {
String message = "<html><body style='font-family: sans-serif; width: 340px; padding: 6px;'>"
+ "<h2 style='margin-bottom: 2px; color: #1a5fb4;'>SimScaleSics</h2>"
+ "<p style='font-size: 11px; color: #666; margin-top: 0;'><b>Industrial Scale Terminal Emulator (v1.5)</b></p>"
+ "<p>Simulatore software di bilance e terminali di pesata su socket TCP/IP con protocollo "
+ "<b>MT-SICS</b> e supporto blocchi <b>MMR</b> (Mettler Toledo). "
+ "Sviluppato per collaudo, test e simulazione di ricette di dosaggio e dispensazione <b>MES / EBR</b>.</p>"
+ "<hr style='border: 0; border-top: 1px solid #ccc;'/>"
+ "<p style='font-size: 11px; line-height: 1.5;'>"
+ "<b>Autori:</b> Antonello Consalvo & G.<br/>"
+ "<b>Email:</b> <a href='mailto:Antonello.consalvo@gmail.com'>Antonello.consalvo@gmail.com</a><br/>"
+ "<b>GitHub:</b> https://github.com/antootto/SimScaleSics.git<br/>"
+ "<b>Licenza:</b> Open Source (MIT License)"
+ "</p>"
+ "</body></html>";
JOptionPane.showMessageDialog(
this,
new JLabel(message),
"About - SimScaleSics",
JOptionPane.INFORMATION_MESSAGE
);
}
private void toggleViewMode() {
isCompactMode = !isCompactMode;
advancedPanel.setVisible(!isCompactMode);
btnToggleView.setText(isCompactMode ? "Vista Estesa [+]" : "Vista Compatta [-]");
pack();
}
private void updateSliderBounds() {
updatingControls = true;
double factor = Math.pow(10, decimalPlaces);
long maxTicks = (long) (maxCapacity * factor);
if (maxTicks > Integer.MAX_VALUE) maxTicks = Integer.MAX_VALUE;
slGrossWeight.setMaximum((int) maxTicks);
syncSliderWithWeight();
updatingControls = false;
}
private void syncSliderWithWeight() {
double factor = Math.pow(10, decimalPlaces);
int tick = (int) Math.round(currentGrossWeight * factor);
slGrossWeight.setValue(Math.min(tick, slGrossWeight.getMaximum()));
}
private synchronized void executeZero() {
currentGrossWeight = 0.0;
tareWeight = 0.0;
SwingUtilities.invokeLater(() -> {
spGrossWeight.setValue(0.0);
slGrossWeight.setValue(0);
});
refreshDisplay();
logMessage("[LOCALE] Tasto ZERO premuto");
}
private synchronized void executeTare() {
tareWeight = currentGrossWeight;
refreshDisplay();
logMessage("[LOCALE] Tasto TARA premuto (" + tareWeight + " " + uom + ")");
}
private synchronized void executeClearTare() {
tareWeight = 0.0;
refreshDisplay();
logMessage("[LOCALE] Tasto CANC. TARA premuto");
}
private synchronized double getNetWeight() {
return currentGrossWeight - tareWeight;
}
private void refreshDisplay() {
SwingUtilities.invokeLater(() -> {
double net = getNetWeight();
String fmt = "%." + decimalPlaces + "f";
String weightFormatted = String.format(Locale.US, fmt, net);
String grossFormatted = String.format(Locale.US, fmt, currentGrossWeight);
String tareFormatted = String.format(Locale.US, fmt, tareWeight);
lblSubInfo.setText("G: " + grossFormatted + " " + uom + " | T: " + tareFormatted + " " + uom);
if (isOverload || currentGrossWeight > maxCapacity) {
lblDisplayWeight.setText("-----^-");
lblStatusFlag.setText("[ OVERLOAD ]");
lblStatusFlag.setForeground(Color.RED);
} else {
lblDisplayWeight.setText(weightFormatted);
String mode = (tareWeight > 0.000001 ? "NET" : "GROSS");
String stability = (isStable ? "STABLE" : "DYN");
lblStatusFlag.setText("[ " + mode + " | " + stability + " ]");
lblStatusFlag.setForeground(isStable ? new Color(50, 205, 50) : Color.ORANGE);
}
});
}
private synchronized String formatSicsWeight(char statusIndicator) {
if (isOverload || currentGrossWeight > maxCapacity) return "S +\r\n";
if (currentGrossWeight < -0.000001) return "S -\r\n";
double net = getNetWeight();
String fmt = "%." + decimalPlaces + "f";
String valStr = String.format(Locale.US, fmt, net);
String formattedVal = String.format(Locale.US, "%10s", valStr);
return String.format(Locale.US, "S %c %s %s\r\n", statusIndicator, formattedVal, uom);
}
private synchronized String processCommand(String rawCmd) {
String cmd = rawCmd.trim();
logMessage("RX <- " + cmd);
if (cmd.isEmpty()) return "";
String response;
if (cmd.equals("S")) {
char st = isStable ? 'S' : 'D';
response = formatSicsWeight(st);
} else if (cmd.equals("SI")) {
char st = isStable ? 'S' : 'D';
response = formatSicsWeight(st);
} else if (cmd.startsWith("TA ")) {
try {
String[] parts = cmd.split("\\s+");
tareWeight = Double.parseDouble(parts[1]);
refreshDisplay();
String fmt = "%." + decimalPlaces + "f";
String valStr = String.format(Locale.US, fmt, tareWeight);
response = String.format(Locale.US, "TA A %10s %s\r\n", valStr, uom);
} catch (Exception e) {
response = "TA I\r\n";
}
} else if (cmd.startsWith("SNS")) {
response = cmd.contains("?") ? "SNS A 1\r\n" : "SNS A\r\n";
} else if (cmd.startsWith("AR 010") || cmd.startsWith("AR 10")) {
response = "AB 1\r\n";
} else if (cmd.startsWith("AR")) {
response = "AB A\r\n";
} else if (cmd.equals("Z")) {
executeZero();
response = "Z A\r\n";
} else if (cmd.equals("T")) {
executeTare();
String fmt = "%." + decimalPlaces + "f";
String valStr = String.format(Locale.US, fmt, tareWeight);
response = String.format(Locale.US, "T S %10s %s\r\n", valStr, uom);
} else if (cmd.equals("TAC")) {
executeClearTare();
response = "TAC A\r\n";
} else if (cmd.startsWith("I2")) {
response = "I2 A \"CONSALVO-G SIMSCALESICS v1.5\"\r\n";
} else if (cmd.startsWith("I4")) {
response = "I4 A \"CG-SCALE\" \"SN-8823411\"\r\n";
} else if (cmd.startsWith("I3") || cmd.startsWith("I1")) {
response = cmd.substring(0, 2) + " A \"OK\"\r\n";
} else {
response = "ES\r\n";
}
if (!response.isEmpty()) {
logMessage("TX -> " + response.trim());
}
return response;
}
private void logMessage(String msg) {
SwingUtilities.invokeLater(() -> {
txtLog.append(msg + "\n");
txtLog.setCaretPosition(txtLog.getDocument().getLength());
});
}
private synchronized void startServer() {
String ipStr = txtBindIp.getText().trim();
int port;
try {
port = Integer.parseInt(txtPort.getText().trim());
} catch (Exception e) {
port = 4001;
}
final int targetPort = port;
serverThread = new Thread(() -> {
try {
InetAddress bindAddr = InetAddress.getByName(ipStr);
serverSocket = new ServerSocket(targetPort, 50, bindAddr);
isRunning = true;
logMessage("Server attivo su " + ipStr + ":" + targetPort);
while (isRunning && !serverSocket.isClosed()) {
Socket clientSocket = serverSocket.accept();
clientSocket.setTcpNoDelay(true);
logMessage("Client connesso: " + clientSocket.getRemoteSocketAddress());
new Thread(() -> handleClient(clientSocket)).start();
}
} catch (Exception e) {
if (isRunning) logMessage("Errore server: " + e.getMessage());
}
});
serverThread.setDaemon(true);
serverThread.start();
}
private void stopServer() {
isRunning = false;
try {
if (serverSocket != null && !serverSocket.isClosed()) serverSocket.close();
} catch (Exception ignored) {}
}
private void restartServer() {
stopServer();
logMessage("Riavvio server...");
startServer();
}
private void handleClient(Socket socket) {
try (
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII));
OutputStream out = socket.getOutputStream()
) {
String line;
while ((line = reader.readLine()) != null) {
String reply = processCommand(line);
if (!reply.isEmpty()) {
out.write(reply.getBytes(StandardCharsets.US_ASCII));
out.flush();
}
}
} catch (Exception ignored) {
} finally {
logMessage("Client disconnesso.");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new SimScaleSics().setVisible(true));
}
}