while (true){ System.out.println("In attesa di chiamate dai Client... "); Socket socket = serverSocket.accept(); System.out.println("Ho ricevuto una chiamata di apertura da:\n" + socket); Protocol serverThread = new Protocol(socket); serverThread.start(); } } public static void main(String[] args) throws Exception{ MathServer server = new MathServer(); server.start(); } }
e successivamente la classe protocol ove vi è implementato il protocollo
//Prtotocol class import java.net.*; import java.io.*;
public class Protocol extends Thread { private Socket clientSocket; public Protocol(Socket socket){ this.clientSocket = socket; }
public void run (){ try { PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; String outputLine; outputLine = "CONNECTED"; out.println(outputLine);
boolean control = false;
while ((inputLine = in.readLine()) != null && control == false) { if (inputLine.equals("SUM")){ int OP1; int OP2; outputLine = "OP1"; out.println(outputLine); while ((inputLine = in.readLine()) != null) { OP1 = Integer.parseInt(inputLine); outputLine = "OP2"; out.println(outputLine); while ((inputLine = in.readLine()) != null) { OP2 = Integer.parseInt(inputLine); int rst = OP1 + OP2; outputLine = "il risulato è " + rst; out.println(outputLine); break; } break; } } else if (inputLine.equals("SUB")){ int OP1; int OP2; out.println("OP1"); while ((inputLine = in.readLine()) != null) { OP1 = Integer.parseInt(inputLine); out.println("OP2"); while ((inputLine = in.readLine()) != null) { OP2 = Integer.parseInt(inputLine); int rst = OP1 - OP2; out.println("il risulato è " + rst); break; } break; } } else if (inputLine.equals("QUIT")){ out.println("CONNESSIONE TERMINATA"); control = true; break; } outputLine = "CONNECTED"; out.println(outputLine); } out.close(); in.close(); clientSocket.close();