Drawer.java
import objectdraw.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
// This class manages the communication for the user doing the drawing.
public class Drawer extends ActiveObject {
// UI component that displays the guesser's guesses.
private Label guessLabel;
// Server connection
private ServerSocket drawingServer;
// Socket that the drawer uses to communicate with the guesser
private Socket drawingSocket;
// Output stream used to write Lines to the guesser.
private ObjectOutputStream out;
// Stream that guesses arrive on
private BufferedReader guessStream;
private static final int TIMEOUT = 60000; // 1 minute
// Create a new drawer. The drawer acts as a server.
// Parameters:
// pictionaryPort - the port that Pictionary uses for communication
// theGuessLabel - the UI component where guesses should be displayed
// when they arrive over the socket's input stream
public Drawer (int pictionaryPort, Label theGuessLabel) {
guessLabel = theGuessLabel;
try {
// Register as a server
drawingServer = new ServerSocket (pictionaryPort);
// Set a timeout for how long to wait for the client to
// connect.
drawingServer.setSoTimeout (TIMEOUT);
// Wait for the client to connect.
drawingSocket = drawingServer.accept();
// Initialize the output stream used to send Lines to the guesser.
out = new ObjectOutputStream (
drawingSocket.getOutputStream());
// Initialize the input stream where the guesses arrive.
guessStream = new BufferedReader (
new InputStreamReader (
drawingSocket.getInputStream()));
} catch (InterruptedIOException e) {
System.out.println ("Connection timed out. Closing server.");
close();
return;
} catch (IOException e) {
System.out.println ("Could not create server.");
System.out.println (e);
close();
return;
}
start();
}
// Accept user guesses on the input stream and display them in the
// guess label.
public void run () {
// -- Repeatedly display the guesses to the drawer as they arrive.
// -- quit when guessStream goes away (i.e., readLine() throws exception)
// Your code here!
// Clean up by closing the stream, socket, and shutting down the server
// connection.
close();
}
// Write a line onto the output stream so that the guesser can see it.
// Be sure to close() if anything goes wrong.
// Parameter
// nextScribble - the line to pass to the guesser
public void writeLine (Line nextScribble) {
// your code here
}
public void quit ()
{
close();
}
// Close everything that is still open.
private void close ()
{
try {
if (out != null)
{
out.close();
}
} catch (IOException e) { }
try {
if (guessStream != null)
{
guessStream.close();
}
} catch (IOException e) { }
try {
if (drawingSocket != null)
{
drawingSocket.close();
}
} catch (IOException e) { }
try {
if (drawingServer != null)
{
drawingServer.close();
}
} catch (IOException e) { }
}
}