001package edu.pdx.cs410J.net; 002 003import java.io.*; 004import java.util.*; 005 006/** 007 * This class allows two people to chat. 008 */ 009public class ChatSession { 010 private static PrintStream out = System.out; 011 private static PrintStream err = System.err; 012 013 /** 014 * Main program that reads lines of text from the console, composes 015 * messages from them, and receives messages from the the listener. 016 * The owner, host, and port numbers for the 017 * <code>ChatSession</code> are read from the command line. 018 */ 019 public static void main(String[] args) { 020 String owner = args[0]; 021 int port = 0; 022 023 try { 024 port = Integer.parseInt(args[1]); 025 026 } catch (NumberFormatException ex) { 027 err.println("** Bad port number: " + args[1]); 028 } 029 030 out.println("Establishing connection"); 031 032 // Make a new ChatCommunicate and start it up 033 ChatCommunicator communicator = new ChatCommunicator(port); 034 communicator.startup(); 035 036 // Prompt for input, read from the command line until the "bye" 037 // message is inputted. 038 try { 039 InputStreamReader isr = new InputStreamReader(System.in); 040 BufferedReader br = new BufferedReader(isr); 041 042 String line = ""; 043 while (!line.trim().equals("bye")) { 044 // Print and read messages from the listener 045 Iterator messages = communicator.getMessages().iterator(); 046 while(messages.hasNext()) { 047 out.println(messages.next()); 048 } 049 050 // Prompt for user input 051 out.print(owner + "> "); 052 out.flush(); 053 054 line = br.readLine(); 055 056 if(!line.trim().equals("")) { 057 ChatMessage message = new ChatMessage(owner, line); 058 communicator.sendMessage(message); 059 } 060 } 061 062 out.println("Waiting for other side to shut down"); 063 064 } catch (IOException ex) { 065 err.println("** IOException: " + ex); 066 System.exit(1); 067 } 068 } 069 070}