Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.InetAddress;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import java.util.Scanner;
- public class EchoClient {
- static final int PORT = 9984;
- static Scanner kb = new Scanner(System.in);
- public static void main(String[] args) throws IOException {
- System.out.println("Please choose an option:");
- int option = 0;
- System.out.println("Host [1]");
- System.out.println("Connect [2]");
- while (true) {
- try {
- option = kb.nextInt();
- break;
- } catch (Exception e) {
- System.err.println("That option is invalid!");
- kb.nextLine();
- }
- }
- switch (option) {
- case 1:
- System.out.println("Hosting converstation...");
- host();
- break;
- case 2:
- System.out.println("Connect to what host?");
- String connectHost = "";
- while (true) {
- try {
- connectHost = kb.nextLine();
- break;
- } catch (Exception e) {
- System.err.println("That option is invalid!");
- kb.nextLine();
- }
- }
- client(connectHost);
- }
- }
- public static void host() {
- System.out.println("Running on port " + PORT + ".");
- try {
- System.out.println(InetAddress.getLocalHost());
- } catch (UnknownHostException e1) {
- System.out.println("Issue finding IP.");
- }
- while (true) {
- try (
- ServerSocket serverSocket =
- new ServerSocket(PORT);
- Socket clientSocket = serverSocket.accept();
- PrintWriter out =
- new PrintWriter(clientSocket.getOutputStream(), true);
- BufferedReader in = new BufferedReader(
- new InputStreamReader(clientSocket.getInputStream()));
- ) {
- String inputLine;
- while ((inputLine = in.readLine()) != null) {
- out.println(inputLine);
- }
- } catch (IOException e) {
- System.out.println("Exception caught when trying to listen on port "
- + PORT + " or listening for a connection.");
- System.out.println(e.getMessage());
- }
- }
- }
- public static void client(String HOST) {
- try (
- Socket echoSocket = new Socket(HOST, PORT);
- PrintWriter out =
- new PrintWriter(echoSocket.getOutputStream(), true);
- BufferedReader in =
- new BufferedReader(
- new InputStreamReader(echoSocket.getInputStream()));
- BufferedReader stdIn =
- new BufferedReader(
- new InputStreamReader(System.in))
- ) {
- String userInput;
- while ((userInput = stdIn.readLine()) != null) {
- out.println(userInput);
- System.out.println(in.readLine());
- }
- } catch (UnknownHostException e) {
- System.err.println("Host " + HOST + " is looking pretty fishy there, bud.");
- System.exit(1);
- } catch (IOException e) {
- System.err.println("Couldn't get I/O for the connection to " + HOST);
- System.exit(1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement