Something went wrong on our end
BavlsikClient.java 2.43 KiB
package MV3500Cohort2024JulySeptember.homework2.Bavlsik;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
/**
* This client attempts to connect to a desired server. If the client is unable
* to connect then it exits the program. Enter 'quit' to the command line at any
* time to exit.
* @author tbavlsik
*/
public class BavlsikClient {
/**
* Localhost address.
*/
public final static String LOCALHOST = "0:0:0:0:0:0:0:1"; //Local host
/**
* @param args the command line arguments
* @throws java.lang.Exception
*/
public static void main(String[] args) throws Exception {
Socket socket = new Socket(LOCALHOST, 2317);
Thread readerThread = new Thread(new Reader(socket));
readerThread.start();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String msg = scanner.nextLine();
//If the client wants to exit, type quit and close the socket
if(msg.equalsIgnoreCase("quit")){
socket.close();
}
//Checks to see if client or server closed socket, if so, end the program
if (socket.isClosed()) {
System.out.println("Connection closed. Exiting...");
break;
}
else{
out.println(msg);
}
}
readerThread.join();
}
private static class Reader implements Runnable {
private BufferedReader in;
private Socket socket;
public Reader(Socket socket) throws IOException {
this.socket = socket;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
@Override
public void run() {
try {
String message;
while ((message = in.readLine()) != null) {
System.out.println(message);
}
} catch (IOException e) {
System.out.println("Disconnected from server.");
} finally {
try {
socket.close();
} catch (IOException e) {
System.out.println("Error closing socket: " + e);
}
}
}
}
}