TooTallNate / Java-WebSocket

A barebones WebSocket client and server implementation written in 100% Java.
http://tootallnate.github.io/Java-WebSocket
MIT License
10.47k stars 2.57k forks source link

Question: Understanding run() #1311

Closed Varshaav16 closed 1 year ago

Varshaav16 commented 1 year ago

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

PhilipRoman commented 1 year ago

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.

PhilipRoman commented 1 year ago

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().

Varshaav16 commented 1 year ago

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.

PhilipRoman commented 1 year ago

Yes, exactly

Varshaav16 commented 1 year ago

thanks