package com.evanram.code.java.dimchat_client_gui;
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 Connections
{
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 static Socket socket;
public Connections()
{
establishConnection(Connections.address, Connections.port);
}
public Connections(String address, int port)
{
establishConnection(address, port);
}
public Connections(String address)
{
establishConnection(address, Connections.port);
}
public Connections(int port)
{
establishConnection(Connections.address, port);
}
private static void establishConnection(String address, int port)
{
try
{
GUI.setText("[dimchat] Establishing connection with " + address + ":" + port + ".");
socket = new Socket(address, port); //create socket
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Message.logInfo("Connected!");
stream(); //send&show server stream
}
catch(UnknownHostException e)
{
Message.logError("Disconnect. Unknown host: \'" + address + "\'");
closeSocket();
Client.newConnection();
return;
}
catch(IOException e)
{
Message.logError("Disconnect. Encountered IOException. (No server running on this port)");
Client.newConnection();
return;
}
}
public static void closeSocket()
{
try
{
if(socket != null)
socket.close();
}
catch(Exception e)
{
Message.logError("Error when closing socket. Please restart application.");
GUI.disableAllButtons();
}
}
private 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!");
Client.newConnection();
return;
}
}
private 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();
}
}