I'm learning to code in Java. I want to write simple chat with gui. So far my application works through command line. I'm interested to build up gui to client part. I have trouble connectiong gui to it. My question is do I have to write special class for gui and than construct such an object in client class and operate on it? In particular I have a problem with establishing communication between client and server via gui. My command line application code as for client part goes as follows. I would appreciate any advice on this matter.
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 4444);
System.out.println("CLIENT: Server connected on port 4444");
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("CLIENT: IN and OUT streams opened. Starting sending data...");
ClientInputThread thread = new ClientInputThread(socket);
thread.start();
String serverResponse;
while ((serverResponse = in.readLine()) != null) {
System.out.println("Server: " + serverResponse);
if (serverResponse.equals("koniec")) {
break;
}
}
System.out.println("CLIENT: Ending server connection. Closing client streams and socket.");
out.close();
in.close();
socket.close();
System.exit(0);
}
catch (UnknownHostException e) {
System.err.println("CLIENT: Trying to connect to unknown host: " + e);
System.exit(1);
}
catch (Exception e) {
System.err.println("CLIENT: Exception: " + e);
System.exit(1);
}
}
}
and
public class ClientInputThread extends Thread {
private PrintWriter out;
public ClientInputThread(Socket clientSocket) {
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
public void run() {
try {
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String userInput="";
while (userInput != null) {
userInput = console.readLine();
out.println(userInput);
out.flush();
if (userInput.equals("koniec")) {
break;
}
}
System.exit(0);
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}