Java - Trenes(Cliente/servidor)

 
Vista:

Trenes(Cliente/servidor)

Publicado por Dani (1 intervención) el 22/10/2016 16:34:19
Saludos, necesito una ayuda, llevo literalmente 12 horas con esto y no e avanzado nada.Soy completamente incapaz ahora mismo estoy supersaturado si alguien me puede echar una mano se lo agradecería eternamente.
un saludo

Debo realizar un programa (cliente/servidor) para reservar asientos en un tren en el cual el servidor estará
constantemente esperando peticiones de reserva y cuando le llegue una, comprobará si esta
libre, ocupada o el tren está lleno y en función de esto le devolverá el resultado al cliente
(RESERVADO, OCUPADO, TREN LLENO).
Para representar el tren e usado una matriz como la siguiente

0 0 0 0
0 0 0 0
0 1 0 0
0 0 0 0

Donde pone 1 es un asiento ocupado
Conforme el servidor vaya reservando plazas mostrara un mapa de los asientos libres y
ocupados.
El cliente enviará al servidor la fila y el vagón (3,2) que quiere reservar el servidor hará las
comprobaciones necesarias contestando al cliente y mostrando este por pantalla el resultado
(RESERVADO, OCUPADO, TREN LLENO).
Habrá un servidor y un máximo de 5 clientes en marcha.
NO es necesario entrada por teclado, el cliente envía una petición a piño fijo.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Trenes(Cliente/servidor)

Publicado por Tom (1831 intervenciones) el 27/10/2016 21:27:22
Algo parecido a esto (hecho rápido y sin probar) podría valer (hacer el cliente sería trivial):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package lwp;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.BitSet;
 
public class TrainServer {
	private final Train t;
	private final ServerSocket	ss;
	public enum Result {OK, CANCEL, FULL, BAD};
 
	/* */
	private TrainServer(Train t) throws IOException {
		this.t = t;
		ss = new ServerSocket(8181);
	}
	/* */
	private void start() throws IOException {
		System.out.println("Server accepting requests on port 8181");
 
		while(true) {
			try(Socket cs = ss.accept()) {
				final ObjectOutputStream os = new ObjectOutputStream(cs.getOutputStream());
				final ObjectInputStream is = new ObjectInputStream(cs.getInputStream());
 
				new Thread() {
					@Override
					public void run() {
						while(true) {
							try {
								Reservation rs = (Reservation)is.readObject();
								System.out.printf("%d, %d\n", rs.wagon, rs.seat);
 
								ReservationResult status = t.takeSeat(rs);
 
								os.writeObject(status);
								t.showFullStatus();
							} catch(IOException | ClassNotFoundException ex) {
								System.err.println("Can't read petition. Reason: " + ex.getMessage());
								ex.printStackTrace();
								//break;
							}
						}
					}
				}.start();
			} catch(IOException x) {
				System.err.println("Can't accept connection. Reason: " + x.getMessage());
			}
		}
	}
 
	/* */
	public static void main(String args[]) throws IOException {
		Train t = new Train();
		TrainServer	ts = new TrainServer(t);
 
		try {
			/* 2 asientos a la izda y 2 a la dcha del pasillo, pasar un múltiplo de 4 */
			t.add(new Wagon(16));
			t.add(new Wagon(32));
		} catch(BadSeatException ex) {
			System.err.println("Error in creation");
			System.exit(1);
		}
 
		ts.start();
	}
	/* */
	static class Train {
		ArrayList<Wagon> convoy;
		private boolean isFull;
 
		/* */
		protected Train() {
			convoy = new ArrayList();
			isFull = true;
		}
		/* */
		protected void add(Wagon w) {
			convoy.add(w);
			isFull = false;
		}
		/* */
		protected synchronized ReservationResult takeSeat(Reservation rs) {
			if(isFull) {
				return new ReservationResult(rs, Result.FULL);
			}
			try {
				boolean ok = take(rs.wagon, rs.seat);
 
				if(ok) {
					for(Wagon w : convoy) {
						isFull = w.isFull ^ isFull;
					}
					return new ReservationResult(rs, Result.OK);
				}
				return new ReservationResult(rs, Result.CANCEL);
			} catch(IndexOutOfBoundsException | BadSeatException ex) {
				System.err.printf("Bad petition (Wagon %d, Seat %d)\n", rs.wagon, rs.seat);
				return new ReservationResult(rs, Result.BAD);
			}
		}
		/* */
		private boolean take(int wagon, int seat) throws BadSeatException {
			try {
				Wagon w = convoy.get(wagon -1);
				return w.takeSeat(seat);
			} catch(IndexOutOfBoundsException x) {
				throw new BadSeatException();
			}
		}
		/* */
		protected void showFullStatus() {
			System.out.println("After last petition: ");
			for(int i = 0; i < 4; i++) {
				for(Wagon w : convoy) {
					System.out.printf("%s ", w.rowString(i));
				}
				System.out.println();
			}
		}
	}
 
	/* */
	static class Wagon {
		private final int capacity;
		private final BitSet	seats;
		private boolean isFull;
		/* */
		protected Wagon(int cap) throws BadSeatException {
			if((cap <= 0) || (cap > 64)) {
				throw new BadSeatException();
			}
			this.capacity = cap;
			seats = new BitSet(cap);
			isFull = false;
		}
		/* */
		protected boolean takeSeat(int seat) throws BadSeatException {
			if((seat < 0) || (seat > capacity)) {
				throw new BadSeatException();
			}
			if(isFull) {
				return false;
			}
			return take(seat - 1);
		}
		/* */
		private boolean take(int seat) {
			if(seats.get(seat)) {
				return false;
			}
			seats.set(seat);
			isFull = seats.nextClearBit(0) >= capacity;
			return true;
		}
		/* 0 ventanilla dcha, 1 pasillo dcha, 2 pasillo izda, 3 ventanilla izda (por ejemplo) */
		private String rowString(int r) {
			StringBuilder sb = new StringBuilder();
			for(int i = r; i < capacity; i += 3) {
				sb.append((seats.get(i)) ? "*" : "_");
			}
			return sb.toString();
		}
	}
	/* */
	public static class Reservation {
		public int	wagon, seat;
		/* */
		Reservation(int w, int s) {
			wagon = w;
			seat = s;
		}
	}
	/* */
	public static class ReservationResult extends Reservation {
		Result	result;
		/* */
		ReservationResult(Reservation rs, Result status) {
			super(rs.wagon, rs.seat);
			result = status;
		}
	}
	/* */
	private static class BadSeatException extends Exception {
		public BadSeatException() {
			super();
		}
	}
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Trenes(Cliente/servidor)

Publicado por Tom (1831 intervenciones) el 28/10/2016 10:01:00
El código que he puesto contiene -por lo menos- un fallo garrafal, de novato, motivado por la precipitación.
Buscarlo puede ser un buen entrenamiento ...
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar