-----------------------------------------------------------------------------------------------------------------------------public class handle extends Thread {
int _port;
String _texto;
DatagramSocket _serverSocket;
InetAddress _IPAddress;
int _clientPort;
boolean _list = false;
boolean doGet=true;
private OutputStream dataOs;
private PrintWriter dataWriter;
private byte[] buff = new byte[1024];
public handle(boolean list, int port, String texto,
DatagramSocket serverSocket, InetAddress IPAddress, int clientPort) {
[Link]("ENTRA HANDLE");
_texto = texto;
_list = list;
_port = port;
_serverSocket = serverSocket;
_IPAddress = IPAddress;
_clientPort = clientPort;
}
public
boolean
do_get(String name,Socket clientSock) {
File inFile = new File(name);
boolean ok = true;
if ([Link]()) {
BufferedInputStream fileStream;
BufferedOutputStream dataOut;
try {
fileStream = new BufferedInputStream (new
FileInputStream(inFile));
dataOut = new
BufferedOutputStream([Link]());
[Link]([Link]());
int recv = 0;
while ((recv = [Link](buff)) != -1) {
//
[Link]("entrando donde debo" +recv);
[Link](buff,0,recv);
}
[Link]();
[Link]();
[Link]("mandando archivo " + name + " de tamanio:
"+[Link]());
ok=true;
} catch (IOException e) {
[Link]("Error ENVIO archivo." + e);
}
} else {
[Link]("El archivo " + inFile + " no existe.");
ok=false;
}
return ok;
}
public void do_list() {
Path currentPath = [Link](".");
File[] dirList = [Link]().listFiles();
for (File f : dirList) {
[Link]([Link]());
[Link]([Link]());
}
[Link]("-1");
[Link]("$");
}
public void run() {
if ( _list) {
ServerSocket servsock = null;
try {
servsock = new ServerSocket(_port);
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
}
[Link]("Esperando cliente TCP para datos...");
Socket sock = null;
try {
sock = [Link]();
} catch (SocketException e) {
// TODO Auto-generated catch block
[Link]();
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
}
[Link]("Conexion aceptada en socket : " + sock);
// LIST
try {
dataOs = [Link]();
dataWriter = new PrintWriter(dataOs,true);
} catch (IOException e1) {
// TODO Auto-generated catch block
[Link]();
}
do_list();
try {
[Link]();
[Link]();
[Link]("Cierro conexion datos tcp");
} catch (IOException e1) {
// TODO Auto-generated catch block
[Link]();
}
} else {
[Link]("GET TCP...");
ServerSocket servsock = null;
try {
servsock = new ServerSocket(_port);
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
}
[Link]("Esperando cliente TCP para datos...");
Socket sock = null;
try {
sock = [Link]();
} catch (SocketException e) {
// TODO Auto-generated catch block
[Link]();
} catch (IOException e) {
// TODO Auto-generated catch block
[Link]();
}
[Link]("Conexion aceptada: " + sock);
try {
dataOs = [Link]();
dataWriter = new PrintWriter(dataOs,true);
} catch (IOException e1) {
// TODO Auto-generated catch block
[Link]();
}
doGet=do_get(_texto,sock);
//Ciere sockets
try {
[Link]();
[Link]();
[Link]("Cierre conexion datos TCP");
} catch (IOException e1) {
[Link]();
}
if(doGet==true){
try {
[Link](_serverSocket, "Transfer OK",
_IPAddress, _clientPort);
} catch (IOException e) {
[Link]();
}
}else{
try {
[Link](_serverSocket, "SERVERROR",
_IPAddress, _clientPort);
} catch (IOException e) {
[Link]();
}
}
-----------------------------------------------------------------------------------------------public class Service {
public static final int SIZEMAX = 255; // Maximum size of datagram
public static final int SERVERPORT = 5000; // default server port
static public enum Command {
HELLO, LIST, GET, QUIT, ERROR
};
static public enum Response {
WCOME, OK, PORT, SERVERROR, BYE, UNKNOWN
};
public static Command commandFromString(String textcommand) {
Command comando = null;
if ([Link]("HELLO")) {
comando = [Link];
} else if ([Link]("LIST")) {
comando = [Link];
} else if ([Link]("GET")) {
comando = [Link];
} else if ([Link]("QUIT")) {
comando = [Link];
} else if ([Link]("ERROR")) {
comando = [Link];
}
return comando;
}
public static Response responseFromString(String textresponse) {
// Este en el cliente
Response respuesta = null;
if ([Link]("Welcome to FTP Service...")) {
respuesta = [Link];
} else if ([Link]("Transfer OK")) {
respuesta = [Link];
} else if ([Link]("PORT")) {
respuesta = [Link];
} else if ([Link]("SERVERROR")) {
respuesta = [Link];
} else if ([Link]("Bye...")) {
respuesta = [Link];
} else if ([Link]("Command Error, try again")) {
respuesta = [Link];
}
return respuesta;
}
public static String requestedFile(String textcommand) {
String fichero;
fichero = [Link](4);
return fichero;
}
public static int portFromResponse(String textresponse) {
String puerto = [Link](5);
return [Link](puerto);
}
public static void sendUDPresponse(DatagramSocket serverSocket, String response,
InetAddress IPAddress, int port)
throws IOException {
// Buffer de salida
byte[] sendData = [Link]();
// Crea paquete de env-o
DatagramPacket sendPacket = new DatagramPacket(sendData, [Link],
IPAddress, port);
// Manda paquete a travs del socket
[Link](sendPacket);
}
public static void sendUDPcommand(DatagramSocket clientSocket, String sentence,
InetAddress IPAddress, int port) throws IOException {
byte[] sendData = [Link](); // Paso String a bytes
DatagramPacket sendPacket = new DatagramPacket(sendData, [Link],
IPAddress, port);
[Link](sendPacket); // Mando el paquete
}
----------------------------------------------------------------------------------------------public class cliente {
private static Scanner dataScanner;
static DatagramPacket receivePacket;
static boolean quit;
static boolean ok;
private static InputStream dataIs;
private static OutputStream dataOs;
private static PrintWriter dataWriter;
private static Scanner userInputScanner;
private static byte[] buff = new byte[1024];
static Scanner ctrlScanner;
public static void list() {
[Link]("\nFTP Server contents:");
long size=0;
size=[Link]([Link]());
String fileName = [Link]();
while(size!=-1 || ) {
[Link](fileName+"
"+size+" bytes");
size=[Link]([Link]());
fileName = [Link]();
}
[Link]();
}
private static void do_get(String fileName,Socket dataSocket) {
File outFile = new File(fileName);
BufferedInputStream dataSocketIn;
BufferedOutputStream bos;
try {
[Link]();
dataSocketIn = new BufferedInputStream ([Link]());
bos = new BufferedOutputStream(new FileOutputStream(outFile));
int bytesRead ;
while ((bytesRead = [Link](buff)) != -1) {
[Link](buff,0,bytesRead);
[Link]();
}
[Link]();
} catch (IOException e) {
[Link]("Error en el
}
get: " +e);
}
public static void main(String[] args) throws IOException {
if (([Link] < 1) || ([Link] > 2)) {
throw new IllegalArgumentException("Introduzca Parmetros: <@IP>
<Puerto>");
}
// Direccin del servidor [Link] para localhost
InetAddress IPAddress = [Link](args[0]);
// Puerto
int servPort = ([Link] == 2) ? [Link](args[1]) : 7;
BufferedReader keyboard = new BufferedReader(new InputStreamReader([Link]));
DatagramSocket clientSocket = new DatagramSocket();
String sentence = "HELLO";
while (!quit) {
byte[] receiveData = new byte[255];
if (sentence != ("HELLO") )
sentence = [Link]();
DatagramPacket receivePacket = new DatagramPacket(receiveData,
[Link]);
[Link] comando = [Link](sentence);
[Link](clientSocket, sentence, IPAddress, servPort);
[Link](receivePacket);
String modifiedSentence = new String([Link](), 0,
[Link]());
[Link] respuesta =
[Link](modifiedSentence);
if(respuesta==[Link])
[Link]("Welcome to FTP Service...");
if (comando!= [Link]){
if(respuesta == [Link]) {
int puerto = [Link](modifiedSentence);
Socket dataSocket = new Socket(IPAddress,puerto);
dataIs = [Link]();
dataOs = [Link]();
dataScanner = new Scanner(dataIs);
dataWriter = new PrintWriter(dataOs,true);
[Link]("Socket Datos en "
+ [Link]() +
" puerto " + [Link]());
userInputScanner = new Scanner([Link]);
if(comando==[Link]) {
String fileName =
[Link](sentence);
do_get(fileName,dataSocket);
[Link]();
[Link]("CIERRE CONEXION DATOS");
[Link](receivePacket);
modifiedSentence = new
String([Link](), 0, [Link]());
[Link] OK =
[Link](modifiedSentence);
if(OK == [Link]){
[Link]("Transfer OK");
}else if(OK ==[Link]){
[Link]("File not found");
}
}else if(comando==[Link]){
[Link]("LIST");
list();
[Link]();
[Link]("CIERRE CONEXION DATOS TCP");
[Link](receivePacket);
modifiedSentence = new
String([Link](), 0, [Link]());
[Link] OK =
[Link](modifiedSentence);
if(OK == [Link]){
[Link]("Transfer
OK");
}else if(OK
==[Link]){
[Link]("Transfer
error");
}
}
}else if(respuesta == [Link]) {
[Link]("Bye...");
quit = true;
}else if(respuesta == [Link]){
[Link]("Command Error, try again");
} else {
comando = [Link];
[Link](respuesta);
[Link]("Comando no admitido introduzca otro:
");
}
}
// [Link](sentence);
sentence ="";
}
[Link]();
}
}
-----------------------------------------------------------------------------------------------
public class servidor {
private static final int ECHOMAX = 255; // Maximum size of echo datagram
public static void main(String[] args) throws IOException {
if ([Link] != 1) { // Puerto del servidor como parmetro
throw new IllegalArgumentException("Introduzca Parmetro: <Puerto>");
}
int servPort = [Link](args[0]);
DatagramSocket serverSocket = new DatagramSocket(5000);
[Link]("Servidor creado con puerto: " + servPort);
byte[] receiveData = new byte[ECHOMAX];
DatagramPacket receivePacket = new DatagramPacket(receiveData,
[Link]);
while (true) {
String response = "";
[Link]("Esperando peticion del cliente...");
// Espera del comando del cliente
[Link](receivePacket);
// Convierte bytes recibidos a String
String sentence = new String([Link](), 0,
[Link]());
// @ IP del cliente
InetAddress IPAddress = [Link]();
int clientPort = [Link]();
[Link]("Handling client at " + [Link]() + " on port " +
[Link] comando = [Link](sentence);
if (comando == [Link]) {
[Link]("HELLO");
response ="Welcome to FTP Service...";
[Link](serverSocket, response, IPAddress,
clientPort);
}
else if (comando == [Link]) {
[Link]("LIST");
int puertoTCP=(int) (([Link]()*3500)+1024);
response = "PORT "+puertoTCP;
[Link](serverSocket, response, IPAddress,
clientPort);
int puerto=[Link](response);
new handle(true, puerto,null, serverSocket, IPAddress,
clientPort).start();
[Link](serverSocket, "Transfer OK", IPAddress,
clientPort);
} else if (comando == [Link]) {
[Link]("get");
String fileName = [Link](sentence);
[Link](fileName);
int puertoTCP=(int) (([Link]()*3500)+1024);
response = "PORT "+puertoTCP;
[Link](serverSocket, response, IPAddress,
clientPort);
new handle(false, puertoTCP,fileName, serverSocket, IPAddress, clientPort).start();
//[Link](serverSocket, "Transfer OK", IPAddress, clientPort);
} else if (comando == [Link]) {
[Link]("BYE");
response ="Bye...";
[Link](serverSocket, response, IPAddress, clientPort);
[Link](response+" abandona servidor FTP el puerto: "+clientPort);
}else{
[Link]("DESCONOCIDO");
response= "UNKNOWN";
[Link](serverSocket, response, IPAddress, clientPort);
}
}
}
}
-----------------------------------------------------------------------------------------------MulticastSocket socket = new MulticastSocket(4446);
InetAddress group = [Link]("[Link]");
[Link](group);
DatagramPacket packet;
for (int i = 0; i < 5; i++) {
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, [Link]);
[Link](packet);
String received = new String([Link]());
[Link]("Quote of the Moment: " + received);
}
[Link](group);
[Link]();
----------------------------------------------------------------------------------------
Cliente Datagrama Java:
import
import
import
import
[Link].*;
[Link].*;
[Link].*;
[Link].*;
public class QuoteClient {
public static void main(String[] args) throws IOException {
if ([Link] != 1) {
[Link]("Usage: java QuoteClient <hostname>");
return;
}
// get a datagram socket
DatagramSocket socket = new DatagramSocket();
// send request
byte[] buf = new byte[256];
String envio = new String("Soy el cliente datagrama");
buf = [Link]();
InetAddress address = [Link](args[0]);
DatagramPacket packet = new DatagramPacket(buf, [Link], address, 4445);
[Link](packet);
// get response
packet = new DatagramPacket(buf, [Link]);
[Link](packet);
// display response
String received = new String([Link](), 0);
[Link]("Quote of the Moment: " + received);
[Link]();
}
}
Servidor Datagrama Java:
import [Link].*;
import [Link].*;
import [Link].*;
public class Server {
public static void main(String[] args) throws IOException {
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, [Link]);
DatagramSocket socket = new DatagramSocket(4445);
[Link](packet);
String recibido = new String([Link](),0);
[Link]("llego paquete: " + recibido);
InetAddress address = [Link]();
int port = [Link]();
packet = new DatagramPacket(buf, [Link], address, port);
[Link](packet);
[Link]();
}
}
Servidor Datagrama Multicast Java:
import [Link].*;
import [Link].*;
import [Link].*;
public class multiServer {
public static void main(String[] args) throws IOException {
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, [Link]);
MulticastSocket socket = new MulticastSocket(4445);
// las direcciones multicast rango: [Link] a [Link]
[Link]([Link](args[0]));
[Link](packet);
String recibido = new String([Link](),0);
[Link]("llego paquete: " + recibido);
InetAddress address = [Link]();
int port = [Link]();
packet = new DatagramPacket(buf, [Link], address, port);
[Link](packet);
[Link]();
}
import [Link];
DINING HALL
public class Monitor {
LinkedList<Long> _colaComensales = new LinkedList<Long>();
int comensales=0;
int salir=0;
int cDentro=0;
boolean permisoSalir=true;
synchronized void comensalLega(int id) {
_colaComensales.add([Link]().getId());
comensales++;
while(!permisoSalir || _colaComensales.getFirst().longValue() !=
[Link]().getId()){
try {
//[Link]("Nio esperando a entrar "+nios);
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
[Link]();
}
}
notifyAll();
comensales--;
cDentro++;
comer(id);
cDentro--;
salir++;
[Link]("quieren salir"+salir+" y dentro hay = "+cDentro);
}
synchronized void comer(int id) {
[Link]("Como y soy el: "+id);
}
synchronized void salir(int id){
if((cDentro==1 && salir==1) ){
permisoSalir=false;
}else if(salir>=2){
salir=salir-2;
permisoSalir=true;
//[Link]("Me largo y soy el: "+id);
[Link]("quieren salir "+salir);
}
}
public static void main(String[] args) {
Monitor monitor = new Monitor();
for (int i = 0; i <50; i++) {
new Comensal(i, monitor).start();
}
}
}
public class Monitor {LANGOSTAS
//Las colas resuelven la innanicion
LinkedList<Long> _colaCamareros = new LinkedList<Long>();
LinkedList<Long> _colaComensales = new LinkedList<Long>();
int capacidad=50;
int langostas=0;
boolean bandejaVacia=true;
synchronized void sirve(int id) {
_colaCamareros.add([Link]().getId());
while(!bandejaVacia || _colaCamareros.getFirst().longValue() !=
[Link]().getId()){
try {
wait();
} catch (InterruptedException e) {
[Link]();
}
}
langostas++;
[Link]("
Sirve camarero "+id);
if(langostas==capacidad){
[Link]("Bandeja llena con "+langostas);
bandejaVacia=false;
}
_colaCamareros.remove();
notifyAll();
}
synchronized void comer(int id) {
_colaComensales.add([Link]().getId());
while(bandejaVacia || _colaComensales.getFirst().longValue() !=
[Link]().getId()){
try {
wait();
} catch (InterruptedException e) {
[Link]();
}
}
if(langostas==0){
bandejaVacia=true;
notifyAll();
}else{
langostas--;
_colaComensales.remove();
[Link]("comiendo comensal
"+id+" quedan "+langostas+"
langostas");
notifyAll();
}
}
public static void main(String[] args) {
Monitor monitor = new Monitor();
for (int i = 0; i <50; i++) {
new Comensal(i, monitor).start();
}
for (int i = 0; i <4; i++) {
new Camarero(i, monitor).start();
}
}
}
----------------------------------------------------------------------------------public class llamante {
public static void main(String[] args) throws IOException {
//se conecta al servidor con invite esta sealizacion e s tcp
if (([Link] < 1) || ([Link] > 2)){ //Comprueba argumentos
throw new IllegalArgumentException("Parameter(s): <Server> [<Port>]");
}
String server = args[0];//IP o nombre del Servidor
String llamada = args[1];//IP o nombre del LLamado
InetAddress address = [Link]();
InetSocketAddress socket=new InetSocketAddress(address,5060+9);
byte[] mensaje=GenerateInvite(llamada,socket);
//envio al server del invite
Socket socketEnvio = new Socket(server, 5060);
DataOutputStream dOut = new DataOutputStream([Link]());
[Link]([Link]); // write length of the message
[Link](mensaje);
// write the message
//esperamos respuesta
String linea="";
new TCPChatClientReceiver(socketEnvio).start();//Hilo escucha cliente.
//rcibimos 200 ok
if([Link]("200 OK")){
//acamos ip y puerto del 200 ok con el substring
//enviamos ack
mensaje=GenerateACK();
//abrimos conexion udp
int puerto=90000;
String destino=[Link](6);
InetAddress dest=[Link](destino);
DatagramSocket socketUDP = new DatagramSocket(puerto);
VoipTransmiter(socketUDP,dest).start();
//nueva conexi tcp para terminar
byte[] bye=GenerateBye();
Socket socketCerrar= new Socket(dest, 5060);
DataOutputStream Out = new DataOutputStream([Link]());
[Link]([Link]); // write length of the message
[Link](bye);
new TCPChatClientReceiver(socketCerrar).start();
if([Link]("200 OK")){
[Link]();
[Link]();
[Link]();
}
}
}
private static byte[] GenerateInvite(String llamada,
InetSocketAddress socketEnvio) {
[Link]("INvite");
return null;
}
}
------------------------------------------------------------------------------------------------------public class Monitor {
LinkedList<Long> zar = new LinkedList<Long>();
LinkedList<Long> hues = new LinkedList<Long>();
int zara=0;
int oscen=0;
boolean turnoZ=true;
boolean turnoH=true;
boolean vacio=true;
synchronized void darTurno(int id) {
while(vacio==true){
if(zara>=oscen){
turnoH=false;
turnoZ=true;
vacio=false;
}else{
turnoH=true;
turnoZ=false;
vacio=false;
}
}
synchronized void llegaZar(int id) {
[Link]([Link]().getId());
while(!vacio || [Link]().longValue() != [Link]().getId()){
try {
wait();
} catch (InterruptedException e) {
[Link]();
}
}
zara++;
[Link]("
Llega zaragoza "+id);
}
synchronized void saleZar(int id) {
if(turnoZ){
[Link]("Pasan los de zarag "+zara+"ocenses "+oscen);
zara=0;
[Link]();
notifyAll();
vacio=true;
}
}
synchronized void llegaOsc(int id) {
[Link]([Link]().getId());
while(!vacio|| [Link]().longValue() != [Link]().getId()){
try {
wait();
} catch (InterruptedException e) {
[Link]();
}
}
oscen++;
[Link]("
Otro oscense "+id);
}
synchronized void saleOsc(int id) {
if(turnoH){
[Link]("Pasan los de huesca "+oscen+"maos "+zara);
oscen=0;
[Link]();
notifyAll();
vacio=true;
}
}
public static void main(String[] args) {
Monitor monitor = new Monitor();
for (int i = 0; i <50; i++) {
new Zargozanos(i, monitor).start();
}
for (int i = 0; i <40; i++) {
new Oscenses(i, monitor).start();}
}
}