Commit ef8abff3 authored by Matti Pulkkinen's avatar Matti Pulkkinen
Browse files

separated streams from SocketHandler

parent f40f9181
package fi.utu.dtek1066;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Main {
public static void main(String[] args) {
// TODO don't throw IOException
public static void main(String[] args) throws IOException {
SocketHandler socketHandler = new SocketHandler();
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
socketHandler.openObjectStreams(ois, oos);
StreamHandler sh = socketHandler.openStreamHandler();
int t = 0;
try {
t = ois.readInt();
t = sh.readInt();
} catch (IOException e) {
System.err.println("Failed in reading t through ObjectInputStream.");
e.printStackTrace();
}
if (t < 2 || t > 10) {
System.err.println("Illegal value t, sending response...");
try {
oos.writeInt(-1);
sh.writeInt(-1);
} catch (IOException e) {
System.out.println("Failed in sending response for illegal value.");
e.printStackTrace();
......
......@@ -79,7 +79,7 @@ public class SocketHandler {
* @param oos
* @throws IOException if opening one of the sockets fails.
*/
public void openObjectStreams(ObjectInputStream ois, ObjectOutputStream oos) throws IOException {
public StreamHandler openStreamHandler() throws IOException {
int timesRetried = 0;
do {
this.sendPortNumber(REMOTEHOST, REMOTEPORT, LOCALPORT);
......@@ -91,10 +91,9 @@ public class SocketHandler {
System.err.println("Failed in setting timeout for socket.");
e.printStackTrace();
}
ois = new ObjectInputStream(this.socket.getInputStream());
oos = new ObjectOutputStream(this.socket.getOutputStream());
break;
return new StreamHandler(new ObjectInputStream(this.socket.getInputStream()),
new ObjectOutputStream(this.socket.getOutputStream()));
} catch (SocketTimeoutException ex) {
System.err.println("Socket timed out, trying again...");
timesRetried++;
......@@ -105,6 +104,8 @@ public class SocketHandler {
System.err.println("Failed to receive connection");
System.exit(1);
}
return null;
} // openObjectStreams()
/**
......
package fi.utu.dtek1066;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class StreamHandler {
private ObjectInputStream ois;
private ObjectOutputStream oos;
public StreamHandler(ObjectInputStream ois, ObjectOutputStream oos) {
this.ois = ois;
this.oos = oos;
}
int readInt() throws IOException {
return this.ois.readInt();
}
void writeInt(int n) throws IOException {
this.oos.writeInt(n);
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment