Question: Understanding run()
Varshaav16 opened this issue · comments
Can you kindly explain what run() does and how is it different from start()?
In this example start() is used to turn on the server
In this example run() is used to turn on the server
start()
starts the server in a new background thread and returns immediately. run()
runs the server loop in the same thread and returns only when server shuts down.
So in the chat server example, it starts server in background because the main thread needs to do more work (read lines from input). But the other example doesn't need to do anything else than run the server, so it just calls run().
Thanks for the fast reply @PhilipRoman
Ex - I have two threads - Thread - A and Thread - B
If I call run()
on thread - A then, I can't call stop()
from the same thread. So I should call stop()
from thread - B
import org.java_websocket.WebSocket;
import java.io.*;
import java.net.InetSocketAddress;
import java.util.*;
public class Server {
public static void main(String[] args) throws IOException, InterruptedException {
String host = "localhost";
int port = 8080;
SimpleServer server = new SimpleServer(new InetSocketAddress(host, port));
server.setConnectionLostTimeout(10);
server.run();
BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Let's start");
while (true) {
String in = sysin.readLine();
System.out.println("Sending: " + in);
server.broadcast(in);
if (in.equals("exit")) {
server.stop();
break;
}
}
System.out.println("--closing--");
sysin.close();
server.stop(1000);
}
}
As I am using run()
, the statements after it won't be executed until server shuts down. Hope I have understood it correctly.
Yes, exactly
thanks