Reputation: 391
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.
Upvotes: 0
Views: 239
Reputation: 2079
That's because the execution of a program (no matter how many classes it has inside) always start with the class containing the "main()" function. As you can see, Main.java is the file holding the main() function and hence execution of this program always starts with that. One of the simplest solutions (not the best) would be to create instances of client in the main function. Hope this helps!
Upvotes: 2