Last active
March 2, 2021 10:37
-
-
Save eloipuertas/9258708 to your computer and use it in GitHub Desktop.
Exemple Client/Servidor usant ComUtils https://gist.github.com/eloipuertas/1f987dfc2e5dcdb57733
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.*; | |
public class Client { | |
public static void main(String[] args) | |
{ | |
String nomMaquina, str; | |
int numPort, value; | |
InetAddress maquinaServidora; | |
Socket socket = null; | |
ComUtils comUtils; | |
if (args.length != 2) | |
{ | |
System.out.println("Us: java Client <maquina_servidora> <port>"); | |
System.exit(1); | |
} | |
nomMaquina = args[0]; | |
numPort = Integer.parseInt(args[1]); | |
try | |
{ | |
/* Obtenim la IP de la maquina servidora */ | |
maquinaServidora = InetAddress.getByName(nomMaquina); | |
/* Obrim una connexio amb el servidor */ | |
socket = new Socket(maquinaServidora, numPort); | |
/* Obrim un flux d'entrada/sortida amb el servidor */ | |
comUtils = new ComUtils(socket); | |
/* Enviem el valor 10 al servidor */ | |
comUtils.write_int32(10); | |
/* Llegim la resposta del servidor */ | |
value = comUtils.read_int32(); | |
System.out.println("He enviat un 10, la resposta del servidor es " + value); | |
/* Tornem a enviar un altre valor */ | |
comUtils.write_int32(12); | |
/* Ara hauriem de rebre un missatge d'error */ | |
value = comUtils.read_int32(); | |
if (value != 99) | |
{ | |
System.out.println("No he rebut un 99 de resposta, sino un " + value); | |
System.exit(1); | |
} | |
else | |
{ | |
str = comUtils.read_string(); | |
System.out.println("He enviat un 12, la resposta és el següent missatge d'error: " + str); | |
} | |
} | |
catch (IOException e) | |
{ | |
System.out.println("Els errors han de ser tractats correctament en el vostre programa."); | |
} | |
finally | |
{ | |
try { | |
if(socket != null) socket.close(); | |
} | |
catch (IOException ex) { | |
System.out.println("Els errors han de ser tractats correctament pel vostre programa"); | |
} // fi del catch | |
} | |
} // fi del main | |
} // fi de la classe | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.*; | |
import java.io.*; | |
import java.util.Locale; | |
public class ComUtils | |
{ | |
/* Mida d'una cadena de caracters */ | |
private final int STRSIZE = 40; | |
/* Objectes per escriure i llegir dades */ | |
private DataInputStream dis; | |
private DataOutputStream dos; | |
public ComUtils(Socket socket) throws IOException | |
{ | |
dis = new DataInputStream(socket.getInputStream()); | |
dos = new DataOutputStream(socket.getOutputStream()); | |
} | |
/* Llegir un enter de 32 bits */ | |
public int read_int32() throws IOException | |
{ | |
byte bytes[] = new byte[4]; | |
bytes = read_bytes(4); | |
return bytesToInt32(bytes,"be"); | |
} | |
/* Escriure un enter de 32 bits */ | |
public void write_int32(int number) throws IOException | |
{ | |
byte bytes[]=new byte[4]; | |
int32ToBytes(number,bytes,"be"); | |
dos.write(bytes, 0, 4); | |
} | |
/* Llegir un string de mida STRSIZE */ | |
public String read_string() throws IOException | |
{ | |
String str; | |
byte bStr[] = new byte[STRSIZE]; | |
char cStr[] = new char[STRSIZE]; | |
bStr = read_bytes(STRSIZE); | |
for(int i = 0; i < STRSIZE;i++) | |
cStr[i]= (char) bStr[i]; | |
str = String.valueOf(cStr); | |
return str.trim(); | |
} | |
/* Escriure un string */ | |
public void write_string(String str) throws IOException | |
{ | |
int numBytes, lenStr; | |
byte bStr[] = new byte[STRSIZE]; | |
lenStr = str.length(); | |
if (lenStr > STRSIZE) | |
numBytes = STRSIZE; | |
else | |
numBytes = lenStr; | |
for(int i = 0; i < numBytes; i++) | |
bStr[i] = (byte) str.charAt(i); | |
for(int i = numBytes; i < STRSIZE; i++) | |
bStr[i] = (byte) ' '; | |
dos.write(bStr, 0,STRSIZE); | |
} | |
/* Passar d'enters a bytes */ | |
private int int32ToBytes(int number,byte bytes[], String endianess) | |
{ | |
if("be".equals(endianess.toLowerCase())) | |
{ | |
bytes[0] = (byte)((number >> 24) & 0xFF); | |
bytes[1] = (byte)((number >> 16) & 0xFF); | |
bytes[2] = (byte)((number >> 8) & 0xFF); | |
bytes[3] = (byte)(number & 0xFF); | |
} | |
else | |
{ | |
bytes[0] = (byte)(number & 0xFF); | |
bytes[1] = (byte)((number >> 8) & 0xFF); | |
bytes[2] = (byte)((number >> 16) & 0xFF); | |
bytes[3] = (byte)((number >> 24) & 0xFF); | |
} | |
return 4; | |
} | |
/* Passar de bytes a enters */ | |
private int bytesToInt32(byte bytes[], String endianess) | |
{ | |
int number; | |
if("be".equals(endianess.toLowerCase())) | |
{ | |
number=((bytes[0] & 0xFF) << 24) | ((bytes[1] & 0xFF) << 16) | | |
((bytes[2] & 0xFF) << 8) | (bytes[3] & 0xFF); | |
} | |
else | |
{ | |
number=(bytes[0] & 0xFF) | ((bytes[1] & 0xFF) << 8) | | |
((bytes[2] & 0xFF) << 16) | ((bytes[3] & 0xFF) << 24); | |
} | |
return number; | |
} | |
//llegir bytes. | |
private byte[] read_bytes(int numBytes) throws IOException{ | |
int len=0 ; | |
byte bStr[] = new byte[numBytes]; | |
do { | |
len += dis.read(bStr, len, numBytes-len); | |
} while (len < numBytes); | |
return bStr; | |
} | |
/* Llegir un string mida variable size = nombre de bytes especifica la longitud*/ | |
public String read_string_variable(int size) throws IOException | |
{ | |
byte bHeader[]=new byte[size]; | |
char cHeader[]=new char[size]; | |
int numBytes=0; | |
// Llegim els bytes que indiquen la mida de l'string | |
bHeader = read_bytes(size); | |
// La mida de l'string ve en format text, per tant creem un string i el parsejem | |
for(int i=0;i<size;i++){ | |
cHeader[i]=(char)bHeader[i]; } | |
numBytes=Integer.parseInt(new String(cHeader)); | |
// Llegim l'string | |
byte bStr[]=new byte[numBytes]; | |
char cStr[]=new char[numBytes]; | |
bStr = read_bytes(numBytes); | |
for(int i=0;i<numBytes;i++) | |
cStr[i]=(char)bStr[i]; | |
return String.valueOf(cStr); | |
} | |
/* Escriure un string mida variable, size = nombre de bytes especifica la longitud */ | |
/* String str = string a escriure.*/ | |
public void write_string_variable(int size,String str) throws IOException | |
{ | |
// Creem una seqüència amb la mida | |
byte bHeader[]=new byte[size]; | |
String strHeader; | |
int numBytes=0; | |
// Creem la capçalera amb el nombre de bytes que codifiquen la mida | |
numBytes=str.length(); | |
strHeader=String.valueOf(numBytes); | |
int len; | |
if ((len=strHeader.length()) < size) | |
for (int i =len; i< size;i++){ | |
strHeader= "0"+strHeader;} | |
System.out.println(strHeader); | |
for(int i=0;i<size;i++) | |
bHeader[i]=(byte)strHeader.charAt(i); | |
// Enviem la capçalera | |
dos.write(bHeader, 0, size); | |
// Enviem l'string writeBytes de DataOutputStrem no envia el byte més alt dels chars. | |
dos.writeBytes(str); | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.*; | |
public class Servidor { | |
public static void main(String[] args) { | |
ServerSocket serverSocket=null; | |
Socket socket=null; | |
ComUtils comUtils; | |
int portServidor = 1234; | |
int value; | |
if (args.length > 1) | |
{ | |
System.out.println("Us: java Servidor [<numPort>]"); | |
System.exit(1); | |
} | |
if (args.length == 1) | |
portServidor = Integer.parseInt(args[0]); | |
try { | |
/* Creem el servidor */ | |
serverSocket = new ServerSocket(portServidor); | |
System.out.println("Servidor socket preparat en el port " + portServidor); | |
while (true) { | |
System.out.println("Esperant una connexió d'un client."); | |
/* Esperem a que un client es connecti amb el servidor */ | |
socket = serverSocket.accept(); | |
System.out.println("Connexió acceptada d'un client."); | |
/* Associem un flux d'entrada/sortida amb el client */ | |
comUtils = new ComUtils(socket); | |
/* Ens esperem a rebre un valor del client */ | |
value = comUtils.read_int32(); | |
System.out.println("He rebut el valor " + value + " del client, ara li envio un 22"); | |
/* Enviem un 22 al client */ | |
comUtils.write_int32(22); | |
/* Tornem a llegir un sencer */ | |
value = comUtils.read_int32(); | |
System.out.println("He rebut un " + value + " del client, ara li responc amb un missatge d'error"); | |
/* Enviem el missatge d'error */ | |
comUtils.write_int32(99); | |
/* Com es que client no rep tot el missatge ? */ | |
comUtils.write_string("Aixo es un exemple de practiques de SD. Bip bip bip bip bip."); | |
} // fi del while infinit | |
} // fi del try | |
catch (IOException ex) { | |
System.out.println("Els errors han de ser tractats correctament pel vostre programa"); | |
} // fi del catch | |
finally | |
{ | |
/* Tanquem la comunicacio amb el client */ | |
try { | |
if(serverSocket != null) serverSocket.close(); | |
} | |
catch (IOException ex) { | |
System.out.println("Els errors han de ser tractats correctament pel vostre programa"); | |
} // fi del catch | |
} | |
} // fi del main | |
} // fi de la classe |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment