Client/Server UDP - JAVA

macGigi

Nuovo Utente
16 Ott 2013
1
0
0
Salve amici, sto provando ad implementare un client-server con protocollo UDP.
Il funzionamento è il seguente: il client prende da tastiera due numeri interi, il server legge questi numeri li somma e manda il risultato al client, il quale lo stampa.
Il problema che sto riscontrando sta nel passaggio di questi interi agli array, mi hanno consigliato di utilizzare ByteArrayInputStream e ByteArrayOutputStream però sinceramente non li ho mai utilizzati e per questo non so come usarli.

Il codice che avevo scritto è il seguente però mi stampa valori sballati
CLIENT

Codice:
import java.io.ByteArrayOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class SumClientUDP {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		
		Scanner sc = new Scanner(System.in); 
		
		// creiamo la socket
		DatagramSocket clientSocket = new DatagramSocket(); 
		
		// indirizzo IP della macchina su cui è avviato il processo
		InetAddress IPAddress = InetAddress.getLocalHost(); 
	        
                System.out.println(IPAddress);
	
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] toSend = baos.toByteArray();
        
                
		byte[] sendData; // = new byte[1024]; 
		byte[] receiveData = new byte[1024]; 
		
		// leggiamo la stringa 
		System.out.println("Effettua la somma di due numeri...");
		System.out.println("Digita il primo numero: ");
		String a = sc.nextLine(); 
		
		System.out.println("Digita il secondo numero: ");
		String b = sc.nextLine(); 
		
		
		// trasformiamo la stringa in array di byte
		sendData = a.getBytes();
		sendData = b.getBytes();
		
		// specifichiamo l'indirizzo di trasporto del server
		DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 1200); 
		
		clientSocket.send(sendPacket); 
		
		// devo predispormi alla ricezione della risposta
		DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
		
		clientSocket.receive(receivePacket); 
		
		String sum = new String(receivePacket.getData()); 
		
		System.out.println("La somma è : " + sum); 
		
		clientSocket.close(); 

	}

}


SERVER

Codice:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class SumServerUDP {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		
		// creiamo la socket con numero di porta 1200
				DatagramSocket serverSocket = new DatagramSocket(1200); 
				
				// dobbiamo creare l'array di byte su cui verranno ricevuti e inviati i dati
				byte[] receiveData = new byte[1024]; 
				byte[] sendData;//  = new byte[1024]; 
				
				while(true) { 
					
					// creiamo una struttura DatagramPacket per riversare i dati letti
					DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
					
					// leggiamo lo standard input
					serverSocket.receive(receivePacket); 
					
					// fino a questo momento abbiamo i byte, questi li dobbiamo trasformare in
					// stringa; si utilizzano i vari metodi
					String a = new String(receivePacket.getData(), 0, receivePacket.getLength()); 
					String b = new String(receivePacket.getData(), 0, receivePacket.getLength()); 
					
					// effetto la somma
					String sum = a + b; 
					
					// ritrasformiamo la stringa in array di byte per poterla spedire
					sendData = sum.getBytes();
					
					// specifichiamo l'indirizzo IP
					InetAddress IPAddress = receivePacket.getAddress(); 
					
					// e il numero di porta
					int port = receivePacket.getPort(); 
					
					DatagramPacket sendPacket = new	DatagramPacket(sendData, sendData.length, IPAddress, port); 
					
					serverSocket.send(sendPacket); 
					
				}

	}

}

Grazie in anticipo a chiunque mi risponderà
 

Marco Frascione

Nuovo Utente
9 Apr 2015
2
0
0
import java.io.*;
import java.net.*;
import java.util.Scanner;


public class SumClientUDP {
public static void main(String[] args) throws Exception {

Scanner inFromUser = new Scanner(System.in);

DatagramSocket clientSocket = new DatagramSocket();

InetAddress IPAddress = InetAddress.getLocalHost();

byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];

ByteArrayOutputStream byteSend = new ByteArrayOutputStream();
DataOutputStream send = new DataOutputStream(byteSend);
ByteArrayInputStream byteReceive;

int a, b, total;

System.out.println("Enter first number: ");
a = inFromUser.nextInt();
send.writeInt(a);

System.out.println("Enter second number: ");
b = inFromUser.nextInt();
send.writeInt(b);

sendData = byteSend.toByteArray();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 1200);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
byteReceive = new ByteArrayInputStream(receivePacket.getData());
DataInputStream receive = new DataInputStream(byteReceive);
total = receive.readInt();
System.out.println("Their sum is " + total);
clientSocket.close();
}
}
 

Marco Frascione

Nuovo Utente
9 Apr 2015
2
0
0
import java.io.*;
import java.net.*;



public class SumServerUDP {

public static void main(String[] args) throws Exception {

DatagramSocket serverSocket = new DatagramSocket(1200);

byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
ByteArrayOutputStream byteSend = new ByteArrayOutputStream();

while(true){
DataOutputStream send = new DataOutputStream(byteSend);
ByteArrayInputStream byteReceive;
int a = 0, b = 0, total = 0;
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
byteReceive = new ByteArrayInputStream(receivePacket.getData());
DataInputStream receive = new DataInputStream(byteReceive);
a = receive.readInt();
b = receive.readInt();
total = a + b;
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
send.writeInt(total);
sendData = byteSend.toByteArray();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
byteSend.reset();
send.close();
receive.close();
}
}
}
 
Discussioni simili
Autore Titolo Forum Risposte Data
C Java client / server Java 0
W [C#] Api RESTFul server/client con cifratura .NET Framework 0
W [C#] Sicurezza Client/Server - SOAP o RESTFull API .NET Framework 0
P [PHP] Caricare un file da client XP su server Ubuntu PHP 2
S [PHP] Errori in lato server ma non in lato client PHP 5
W Server e Client (dati dinamici) PHP 1
MarcoGrazia node.js applicazioni standalone e client/server Javascript 0
P Problema con lettura filesystem del client da server! Upload multiplo foto. PHP 5
M Convertire piccolo codice da lato server a client Javascript 1
E [RISOLTO]Sicurezza attacchi con $_session: come viene gestita nella trasmissione server client ? PHP 5
Ndogni Antonio Gallo server crea nuova pagina html su client PHP 0
D Salvare file su PC client invece che su server - Script XDCC Fetcher PHP 3
N Delphi - Client/server InDy - Errore Read su Stream dal Server Programmazione 0
C Server e client in LAN - Client e Cell in Wi.fi Reti LAN e Wireless 0
A accesso lato client, anzichè lato server PHP 1
Samb1985 Applicazione client server in linguaggio c unix Programmazione 0
N Come monitorare la continuità di connessione di un'applicazione client/server Hardware 0
felino Mac OS e Client Mail: Stato non in linea Mac e Software 1
N client web hikvision IP Cam e Videosorveglianza 10
Chompy_666 Errore 550 /ftp client Server Dedicati e VPS 1
L [WordPress] Errori - Lato client dalla console del browser WordPress 1
A [MySQL] problema con la command line client. MySQL 0
B CLIENT VISUALE MYSQL MySQL 0
C [Java] Client web service con ssl, certificato .cer e trasferimento mtom Java 2
felino Client MAIL: backup email esistenti Mac e Software 1
A Invio Email alla connessione di un Client su Lan Reti LAN e Wireless 2
L Configurazione client FTP integrato in Dreamweaver HTML e CSS 3
A leggere la data del client PHP 1
A client FTP gratis per Mac Mac e Software 1
M pesantezza Javascript client-side Javascript 6
M esecuzione comando shell da applicazione php su client PHP 5
ivarello eseguire exec() lato Client PHP 1
Z Eseguire una Query tramite linguaggi client-side è possibile? Ajax 3
YellowMan Client FTP per Android Smartphone e tablet 1
G Upload file di un client su sito PHP 18
M PEC Aruba: configurare client di posta Posta Elettronica 1
E Modificare sito Web tramite client FTP HTML e CSS 1
F client di posta con php PHP 4
P client voip PHP 7
B Aumentare livello di sicurezza accesso client area riservata Classic ASP 5
F client in c Programmazione 1
O APACHE:[error] [client 127.0.0.1] File does not exist: /var/www/favicon.ico PHP 10
I desktop unico per tutti i client Windows e Software 1
A visualizare file pdf in client side PHP 8
catellostefano Un client di posta in PHP con le funzioni IMAP PHP 5
max1850 Creare un client ftp Classic ASP 8
crocchio Client PHP che dialoga con un Web Service in Java PHP 2
M Semplice php client e web service scritto in c# non funzionanti PHP 0
S Menu e sottomenu client side senza reload della pagina Javascript 1
M Problema per altri client Webdesign e Grafica 0

Discussioni simili