package com.evanram.code.java.chatclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class Client
{
private static String address = "localhost";
private static int port = 38936;
private static String nickname = System.getProperty("user.name");
public static PrintWriter out;
public static BufferedReader in;
public Client()
{
establishConnection(address, port);
}
public static void main(String... args)
{
if(args.length == 1) //set defined address
address = args[0];
else if(args.length > 1) //set defined address:port
{
if(args.length > 2)
{
nickname = args[2];
}
try
{
address = args[0];
port = Integer.parseInt(args[1]);
}
catch(NumberFormatException e)
{
Message.logError("Invalid port! Using default port: " + port);
}
}
new Client(); //try opening connection
}
public static void establishConnection(String address, int port)
{
try
{
Message.log("Establishing connection with " + address + ":" + port + ".");
Socket socket = new Socket(address, port); //create socket
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Message.log("Connected!");
stream(); //send&show server stream
}
catch(UnknownHostException e)
{
Message.logError("Disconnect. Unknown host: \'" + address + "\'");
}
catch(IOException e)
{
Message.logError("Disconnect. Encountered IOException. (No server running on this port)");
}
}
public static void stream()
{
new Thread(new PrintInputStream()).start(); //new thread, read server messages
try
{
for(String s : entryCommands())
{
out.println(s);
}
while(true)
{
String nextInput = Message.nextInputLine(); //get next client input
out.println(nextInput); //send text to server
}
}
catch(Exception e)
{
Message.logError("Connection failed!");
}
}
public static ArrayList<String> entryCommands()
{
ArrayList<String> entryCmds = new ArrayList<String>();
entryCmds.add("!nick " + nickname);
entryCmds.add("!motd");
entryCmds.add("!list");
return entryCmds;
}
public static String getNextInput() throws IOException
{
return in.readLine();
}
public static void flushOutput()
{
out.flush();
}
}