![]() |
Pages (2): « 1 [2] Show 150 posts per page |
.dsy:it. (http://www.dsy.it/forum/)
- Reti di calcolatori (http://www.dsy.it/forum/forumdisplay.php?forumid=68)
-- [ESERCIZIO] Thread (http://www.dsy.it/forum/showthread.php?threadid=14000)
Posto la mia soluzione, naturalmente non è l'unica
Server - Server.java
code:
import java.net.*; import java.io.*; class Server { public static void main(String args[]) { ServerSocket listener = (ServerSocket) null; //necessario altrimenti potrebbe non essere inizializzato Socket established; try { //Apertura socket di ascolto listener = new ServerSocket(7000, 300); } catch(IOException e) {} while(true) { try { System.out.println("Server: In attesa di connessioni..."); established = listener.accept(); /* * Accettazione richiesta di connessione * e passaggio del socket creato ad un nuovo thread */ System.out.println("Server: Connessione accettata e lancio nuovo thread"); (new CliManager(established)).start(); } catch(Exception e) {} } //listener.close(); //codice irraggiungibile a causa del while(true) } }
code:
import java.net.*; import java.io.*; import java.util.Random; class CliManager extends Thread { private Socket passedSocket; private String toSend; private OutputStream sock_out; private static Random rand; // Generatore di numeri casuali public CliManager(Socket s) throws Exception { System.out.println("CliManager: Creazione nuovo CliManager " + getName()); toSend = "Hello Net World!\n"; /* * Ricezione del socket creato dal server * e ottenimento dello stream di output */ passedSocket = s; sock_out = s.getOutputStream(); rand = new Random(); } public void run() { int slength; try { System.out.println(getName() + ": Inizio invio dati al client"); slength = toSend.length(); //Invio carattere per carattere della stringa for(int i = 0; i < slength; i++) { sock_out.write((int) toSend.charAt(i)); sleep((rand.nextInt(4) + 1) * 500); //Attesa casuale tra 0.5 e 2 secondi } System.out.println(getName() + ": Fine invio dati al client"); passedSocket.close(); } catch(Exception e) {} } }
__________________
?
All times are GMT. The time now is 11:17. | Pages (2): « 1 [2] Show all 16 posts from this thread on one page |
Powered by: vBulletin Version 2.3.1
Copyright © Jelsoft Enterprises Limited 2000 - 2002.