001package edu.pdx.cs410J.net; 002 003import java.io.*; 004import java.util.*; 005import java.net.*; 006 007/** 008 * A <code>ChatCommunicator</code> obtains a <code>Socket</code> and 009 * then creates a <code>ChatSpeaker</code> and a 010 * <code>ChatListener</code> that run in their own threads. 011 */ 012public class ChatCommunicator implements Runnable { 013 private static PrintStream err = System.err; 014 015 private int port; // Where the socket is 016 private ChatSpeaker speaker; // Send messsages 017 private ChatListener listener; // Receives messages 018 019 /** 020 * Creates a new <code>ChatCommunicator</code> on a given port. 021 * 022 */ 023 public ChatCommunicator(int port) { 024 this.port = port; 025 } 026 027 /** 028 * Starts up this <code>ChatCommunicator</code>. 029 */ 030 public void startup() { 031 this.speaker = new ChatSpeaker(); 032 this.listener = new ChatListener(); 033 (new Thread(this)).start(); 034 } 035 036 /** 037 * Make the connection to the socket. If it cannot open a 038 * <code>Socket</code>, is starts a <code>SocketServer</code> and 039 * waits for a connection. Then, start the speaker and listener. 040 */ 041 public void run() { 042 // Attempt to make a socket 043 Socket socket = null; 044 try { 045 socket = new Socket("localhost", port); 046 047 } catch (IOException ex) { 048 // Nobody listening 049// System.out.println("Nobody's listening"); 050 } 051 052 if (socket == null) { 053 // Listen 054 try { 055 ServerSocket server = new ServerSocket(port, 10); 056 socket = server.accept(); 057 058 } catch (IOException ex) { 059 err.println("** IOException: " + ex); 060 System.exit(1); 061 } 062 } 063 064 this.speaker.setSocket(socket); 065 this.listener.setSocket(socket); 066 067 (new Thread(this.speaker)).start(); 068 (new Thread(this.listener)).start(); 069 } 070 071 /** 072 * Delegates to the <code>ChatSpeaker</code> 073 */ 074 public void sendMessage(ChatMessage message) { 075 this.speaker.sendMessage(message); 076 } 077 078 /** 079 * Gets messages from the <code>ChatListener</code> 080 */ 081 public List getMessages() { 082 return this.listener.getMessages(); 083 } 084}