I'm relatively new to Java and I've been having a recurring problem that's been frustrating me.
I have two class files in the same Project folder: 'Main.java' & 'Client.java'.
'Main.java' is the server ( I run this first). I try to run Client.java to connect to the server. However, it keeps re-launching 'Main.java' regardless of my attempts to fix this. I have tried tried selecting 'Run As' and 'Run Configuration..' but nothing seems to work. This has happened me in several projects and I cannot seem to figure out a solution.
Here is my code:
1: Main.java
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.util.ArrayList; public class Main { public static void main(String[] args) throws IOException { try { final int PORT = 6677; ServerSocket server = new ServerSocket(PORT); System.out.println("Waiting for clients..."); while (true) { Socket s = server.accept(); System.out.println("Client connected from " + s.getLocalAddress().getHostName()); Client chat = new Client(s); Thread t = new Thread(chat); t.start(); } } catch (Exception e) { System.out.println("An error occured."); e.printStackTrace(); } } } 2: Client.java
import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; public class Client implements Runnable { private Socket socket; public Client(Socket s) { socket = s; } @Override public void run() { try { Scanner in = new Scanner(socket.getInputStream()); PrintWriter out = new PrintWriter(socket.getOutputStream()); while (true) { if (in.hasNext()) { String input = in.nextLine(); System.out.println("Client Said: " + input); out.println("You Said: " + input); out.flush(); } } } catch (Exception e) { e.printStackTrace(); } } } Any help is greatly appreciated.
Thanks.