Public Class Extends: Handle Thread (

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

-----------------------------------------------------------------------------------------------------------------------------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) {
System.out.println("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 (inFile.exists()) {
BufferedInputStream fileStream;
BufferedOutputStream dataOut;
try {
fileStream = new BufferedInputStream (new
FileInputStream(inFile));
dataOut = new
BufferedOutputStream(clientSock.getOutputStream());
dataWriter.println(inFile.length());
int recv = 0;
while ((recv = fileStream.read(buff)) != -1) {
//
System.out.println("entrando donde debo" +recv);
dataOut.write(buff,0,recv);
}
dataOut.flush();
fileStream.close();
System.out.println("mandando archivo " + name + " de tamanio:
"+inFile.length());
ok=true;
} catch (IOException e) {
System.out.println("Error ENVIO archivo." + e);
}
} else {
System.out.println("El archivo " + inFile + " no existe.");
ok=false;
}
return ok;
}
public void do_list() {
Path currentPath = Paths.get(".");
File[] dirList = currentPath.toFile().listFiles();
for (File f : dirList) {
dataWriter.println(f.length());
dataWriter.println(f.getName());
}
dataWriter.println("-1");
dataWriter.println("$");
}
public void run() {
if ( _list) {
ServerSocket servsock = null;
try {
servsock = new ServerSocket(_port);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Esperando cliente TCP para datos...");
Socket sock = null;
try {
sock = servsock.accept();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Conexion aceptada en socket : " + sock);
// LIST
try {
dataOs = sock.getOutputStream();
dataWriter = new PrintWriter(dataOs,true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
do_list();
try {
servsock.close();
sock.close();
System.out.println("Cierro conexion datos tcp");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} else {
System.out.println("GET TCP...");
ServerSocket servsock = null;
try {
servsock = new ServerSocket(_port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Esperando cliente TCP para datos...");
Socket sock = null;
try {
sock = servsock.accept();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Conexion aceptada: " + sock);
try {
dataOs = sock.getOutputStream();
dataWriter = new PrintWriter(dataOs,true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
doGet=do_get(_texto,sock);
//Ciere sockets
try {
servsock.close();
sock.close();

System.out.println("Cierre conexion datos TCP");


} catch (IOException e1) {
e1.printStackTrace();
}
if(doGet==true){
try {
Service.sendUDPresponse(_serverSocket, "Transfer OK",
_IPAddress, _clientPort);
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
Service.sendUDPresponse(_serverSocket, "SERVERROR",
_IPAddress, _clientPort);
} catch (IOException e) {
e.printStackTrace();
}
}
-----------------------------------------------------------------------------------------------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 (textcommand.contains("HELLO")) {
comando = Command.HELLO;
} else if (textcommand.contains("LIST")) {
comando = Command.LIST;
} else if (textcommand.contains("GET")) {
comando = Command.GET;
} else if (textcommand.contains("QUIT")) {
comando = Command.QUIT;
} else if (textcommand.contains("ERROR")) {
comando = Command.ERROR;
}
return comando;
}

public static Response responseFromString(String textresponse) {


// Este en el cliente
Response respuesta = null;
if (textresponse.contains("Welcome to FTP Service...")) {
respuesta = Response.WCOME;
} else if (textresponse.contains("Transfer OK")) {
respuesta = Response.OK;
} else if (textresponse.contains("PORT")) {
respuesta = Response.PORT;
} else if (textresponse.contains("SERVERROR")) {
respuesta = Response.SERVERROR;
} else if (textresponse.contains("Bye...")) {
respuesta = Response.BYE;
} else if (textresponse.contains("Command Error, try again")) {
respuesta = Response.UNKNOWN;
}
return respuesta;
}
public static String requestedFile(String textcommand) {

String fichero;
fichero = textcommand.substring(4);
return fichero;
}
public static int portFromResponse(String textresponse) {
String puerto = textresponse.substring(5);
return Integer.parseInt(puerto);
}
public static void sendUDPresponse(DatagramSocket serverSocket, String response,
InetAddress IPAddress, int port)
throws IOException {
// Buffer de salida
byte[] sendData = response.getBytes();
// Crea paquete de env-o
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
IPAddress, port);

// Manda paquete a travs del socket


serverSocket.send(sendPacket);
}
public static void sendUDPcommand(DatagramSocket clientSocket, String sentence,
InetAddress IPAddress, int port) throws IOException {
byte[] sendData = sentence.getBytes(); // Paso String a bytes
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
IPAddress, port);
clientSocket.send(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() {
System.out.println("\nFTP Server contents:");
long size=0;
size=Long.parseLong(dataScanner.nextLine());
String fileName = dataScanner.nextLine();
while(size!=-1 || !fileName.equals("$")) {
System.out.println(fileName+"
"+size+" bytes");
size=Long.parseLong(dataScanner.nextLine());
fileName = dataScanner.nextLine();
}
System.out.println();
}
private static void do_get(String fileName,Socket dataSocket) {
File outFile = new File(fileName);
BufferedInputStream dataSocketIn;
BufferedOutputStream bos;
try {
outFile.createNewFile();
dataSocketIn = new BufferedInputStream (dataSocket.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(outFile));
int bytesRead ;
while ((bytesRead = dataSocketIn.read(buff)) != -1) {

bos.write(buff,0,bytesRead);
bos.flush();
}
bos.close();
} catch (IOException e) {
System.out.println("Error en el
}

get: " +e);

}
public static void main(String[] args) throws IOException {
if ((args.length < 1) || (args.length > 2)) {
throw new IllegalArgumentException("Introduzca Parmetros: <@IP>
<Puerto>");
}
// Direccin del servidor 127.0.0.1 para localhost
InetAddress IPAddress = InetAddress.getByName(args[0]);
// Puerto
int servPort = (args.length == 2) ? Integer.parseInt(args[1]) : 7;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
String sentence = "HELLO";
while (!quit) {
byte[] receiveData = new byte[255];
if (sentence != ("HELLO") )
sentence = keyboard.readLine();
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
Service.Command comando = Service.commandFromString(sentence);
Service.sendUDPcommand(clientSocket, sentence, IPAddress, servPort);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData(), 0,
receivePacket.getLength());
Service.Response respuesta =
Service.responseFromString(modifiedSentence);
if(respuesta==Service.Response.WCOME)
System.out.println("Welcome to FTP Service...");
if (comando!= Service.Command.HELLO){
if(respuesta == Service.Response.PORT) {
int puerto = Service.portFromResponse(modifiedSentence);
Socket dataSocket = new Socket(IPAddress,puerto);
dataIs = dataSocket.getInputStream();
dataOs = dataSocket.getOutputStream();
dataScanner = new Scanner(dataIs);
dataWriter = new PrintWriter(dataOs,true);
System.out.println("Socket Datos en "
+ dataSocket.getInetAddress() +
" puerto " + dataSocket.getPort());
userInputScanner = new Scanner(System.in);
if(comando==Service.Command.GET) {
String fileName =
Service.requestedFile(sentence);
do_get(fileName,dataSocket);
dataSocket.close();
System.out.println("CIERRE CONEXION DATOS");
clientSocket.receive(receivePacket);
modifiedSentence = new
String(receivePacket.getData(), 0, receivePacket.getLength());
Service.Response OK =
Service.responseFromString(modifiedSentence);
if(OK == Service.Response.OK){
System.out.println("Transfer OK");
}else if(OK ==Service.Response.SERVERROR){
System.out.println("File not found");
}
}else if(comando==Service.Command.LIST){
System.out.println("LIST");
list();
dataSocket.close();
System.out.println("CIERRE CONEXION DATOS TCP");

clientSocket.receive(receivePacket);
modifiedSentence = new
String(receivePacket.getData(), 0, receivePacket.getLength());
Service.Response OK =
Service.responseFromString(modifiedSentence);
if(OK == Service.Response.OK){
System.out.println("Transfer
OK");
}else if(OK
==Service.Response.SERVERROR){
System.out.println("Transfer
error");
}
}
}else if(respuesta == Service.Response.BYE) {
System.out.println("Bye...");
quit = true;
}else if(respuesta == Service.Response.UNKNOWN){
System.out.println("Command Error, try again");
} else {
comando = Command.ERROR;
System.out.println(respuesta);
System.out.println("Comando no admitido introduzca otro:
");
}
}
// System.out.println(sentence);
sentence ="";
}
clientSocket.close();
}
}
-----------------------------------------------------------------------------------------------

public class servidor {


private static final int ECHOMAX = 255; // Maximum size of echo datagram
public static void main(String[] args) throws IOException {
if (args.length != 1) { // Puerto del servidor como parmetro
throw new IllegalArgumentException("Introduzca Parmetro: <Puerto>");
}
int servPort = Integer.parseInt(args[0]);
DatagramSocket serverSocket = new DatagramSocket(5000);
System.out.println("Servidor creado con puerto: " + servPort);
byte[] receiveData = new byte[ECHOMAX];
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while (true) {
String response = "";
System.out.println("Esperando peticion del cliente...");
// Espera del comando del cliente
serverSocket.receive(receivePacket);
// Convierte bytes recibidos a String
String sentence = new String(receivePacket.getData(), 0,
receivePacket.getLength());
// @ IP del cliente
InetAddress IPAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
System.out.print("Handling client at " + IPAddress.getHostAddress() + " on port " +
Service.Command comando = Service.commandFromString(sentence);
if (comando == Service.Command.HELLO) {
System.out.println("HELLO");
response ="Welcome to FTP Service...";
Service.sendUDPresponse(serverSocket, response, IPAddress,
clientPort);
}
else if (comando == Service.Command.LIST) {
System.out.println("LIST");
int puertoTCP=(int) ((Math.random()*3500)+1024);

response = "PORT "+puertoTCP;


Service.sendUDPresponse(serverSocket, response, IPAddress,
clientPort);
int puerto=Service.portFromResponse(response);
new handle(true, puerto,null, serverSocket, IPAddress,
clientPort).start();
Service.sendUDPresponse(serverSocket, "Transfer OK", IPAddress,
clientPort);
} else if (comando == Service.Command.GET) {
System.out.println("get");
String fileName = Service.requestedFile(sentence);
System.out.println(fileName);
int puertoTCP=(int) ((Math.random()*3500)+1024);
response = "PORT "+puertoTCP;
Service.sendUDPresponse(serverSocket, response, IPAddress,
clientPort);
new handle(false, puertoTCP,fileName, serverSocket, IPAddress, clientPort).start();
//Service.sendUDPresponse(serverSocket, "Transfer OK", IPAddress, clientPort);
} else if (comando == Service.Command.QUIT) {
System.out.println("BYE");
response ="Bye...";
Service.sendUDPresponse(serverSocket, response, IPAddress, clientPort);
System.out.println(response+" abandona servidor FTP el puerto: "+clientPort);
}else{
System.out.println("DESCONOCIDO");
response= "UNKNOWN";
Service.sendUDPresponse(serverSocket, response, IPAddress, clientPort);
}
}
}
}

-----------------------------------------------------------------------------------------------MulticastSocket socket = new MulticastSocket(4446);


InetAddress group = InetAddress.getByName("203.0.113.0");
socket.joinGroup(group);
DatagramPacket packet;
for (int i = 0; i < 5; i++) {
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData());
System.out.println("Quote of the Moment: " + received);
}
socket.leaveGroup(group);
socket.close();

----------------------------------------------------------------------------------------

Cliente Datagrama Java:


import
import
import
import

java.io.*;
java.net.*;
java.util.*;
java.lang.*;

public class QuoteClient {


public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.out.println("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 = envio.getBytes();
InetAddress address = InetAddress.getByName(args[0]);
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);

socket.send(packet);
// get response
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// display response
String received = new String(packet.getData(), 0);
System.out.println("Quote of the Moment: " + received);
socket.close();
}
}

Servidor Datagrama Java:


import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
public static void main(String[] args) throws IOException {
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
DatagramSocket socket = new DatagramSocket(4445);
socket.receive(packet);
String recibido = new String(packet.getData(),0);
System.out.println("llego paquete: " + recibido);
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
socket.close();

}
}
Servidor Datagrama Multicast Java:
import java.io.*;
import java.net.*;
import java.util.*;
public class multiServer {
public static void main(String[] args) throws IOException {
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
MulticastSocket socket = new MulticastSocket(4445);
// las direcciones multicast rango: 224.0.0.1 a 239.255.255.255
socket.joinGroup(InetAddress.getByeName(args[0]));
socket.receive(packet);
String recibido = new String(packet.getData(),0);
System.out.println("llego paquete: " + recibido);
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
socket.close();

}
import java.util.LinkedList;

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(Thread.currentThread().getId());
comensales++;
while(!permisoSalir || _colaComensales.getFirst().longValue() !=
Thread.currentThread().getId()){
try {

//System.out.println("Nio esperando a entrar "+nios);


wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notifyAll();
comensales--;
cDentro++;
comer(id);
cDentro--;
salir++;
System.out.println("quieren salir"+salir+" y dentro hay = "+cDentro);
}
synchronized void comer(int id) {
System.out.println("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;
//System.out.println("Me largo y soy el: "+id);
System.out.println("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(Thread.currentThread().getId());
while(!bandejaVacia || _colaCamareros.getFirst().longValue() !=
Thread.currentThread().getId()){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
langostas++;
System.out.println("
Sirve camarero "+id);
if(langostas==capacidad){
System.out.println("Bandeja llena con "+langostas);
bandejaVacia=false;
}
_colaCamareros.remove();
notifyAll();
}
synchronized void comer(int id) {
_colaComensales.add(Thread.currentThread().getId());
while(bandejaVacia || _colaComensales.getFirst().longValue() !=
Thread.currentThread().getId()){
try {
wait();
} catch (InterruptedException e) {

e.printStackTrace();
}
}
if(langostas==0){
bandejaVacia=true;
notifyAll();
}else{
langostas--;
_colaComensales.remove();
System.out.println("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 ((args.length < 1) || (args.length > 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 = InetAddress.getLocalHost();
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(socketEnvio.getOutputStream());
dOut.writeInt(mensaje.length); // write length of the message
dOut.write(mensaje);
// write the message
//esperamos respuesta
String linea="";
new TCPChatClientReceiver(socketEnvio).start();//Hilo escucha cliente.
//rcibimos 200 ok
if(linea.equals("200 OK")){
//acamos ip y puerto del 200 ok con el substring
//enviamos ack
mensaje=GenerateACK();
//abrimos conexion udp
int puerto=90000;
String destino=linea.substring(6);
InetAddress dest=InetAddress.getByName(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(socketCerrar.getOutputStream());
Out.writeInt(bye.length); // write length of the message
Out.write(bye);
new TCPChatClientReceiver(socketCerrar).start();
if(linea.equals("200 OK")){
socketEnvio.close();
socketUDP.close();
socketCerrar.close();
}
}
}
private static byte[] GenerateInvite(String llamada,
InetSocketAddress socketEnvio) {
System.out.print("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) {
zar.add(Thread.currentThread().getId());
while(!vacio || zar.getFirst().longValue() != Thread.currentThread().getId()){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
zara++;
System.out.println("
Llega zaragoza "+id);
}
synchronized void saleZar(int id) {
if(turnoZ){
System.out.println("Pasan los de zarag "+zara+"ocenses "+oscen);
zara=0;
zar.remove();
notifyAll();
vacio=true;
}
}
synchronized void llegaOsc(int id) {
hues.add(Thread.currentThread().getId());
while(!vacio|| hues.getFirst().longValue() != Thread.currentThread().getId()){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
oscen++;
System.out.println("
Otro oscense "+id);
}
synchronized void saleOsc(int id) {
if(turnoH){
System.out.println("Pasan los de huesca "+oscen+"maos "+zara);
oscen=0;
hues.remove();
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();}
}
}

You might also like