UDPServer.java 1.24 KB
Newer Older
Gabriele Civitarese's avatar
Gabriele Civitarese committed
1 2 3 4 5 6 7 8 9
import java.io.*; 
import java.net.*; 

class UDPServer { 
	public static void main(String args[]) throws Exception { 
		/* Inizializza la datagram socket specificando la porta di ascolto */

		DatagramSocket serverSocket = new DatagramSocket(9876); 

10 11
		byte[] receiveData; 
		byte[] sendData;
Gabriele Civitarese's avatar
Gabriele Civitarese committed
12 13 14 15

		while(true) 
		{ 

16 17 18
			receiveData = new byte[1024];
			sendData = new byte[1024];

Gabriele Civitarese's avatar
Gabriele Civitarese committed
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
			/* Prepara la struttura dati usata per contenere il pacchetto in ricezione */
			DatagramPacket receivePacket = 
				new DatagramPacket(receiveData, receiveData.length);

			/* Riceve un pacchetto da un client */
			serverSocket.receive(receivePacket); 

			String sentence = new String(receivePacket.getData()); 

			/* Ottiene dal pacchetto informazioni sul mittente */
			InetAddress IPAddress = receivePacket.getAddress(); 
			int port = receivePacket.getPort(); 

			String capitalizedSentence = sentence.toUpperCase(); 

			sendData = capitalizedSentence.getBytes(); 

			/* Prepara il pacchetto da spedire specificando
			 * contenuto, indirizzo e porta del destinatario */
			DatagramPacket sendPacket = 
				new DatagramPacket(sendData, sendData.length, IPAddress, 
						port); 

			/* Invia il pacchetto attraverso la socket */
			serverSocket.send(sendPacket); 
		} 
	} 
}