Java makes proxy socket multithreaded

I created a java proxy and it works but only allows 1 client. I know I need multithreading, so I did this so that it opens new threads, but I can't get it to work for some reason ...

This is my proxy class:

public class Proxy {

    private static ServerSocket server;
    private static int port = 9339;
    private static String originalHost = "game.boombeachgame.com";

    public static void main(String[] args) throws FileNotFoundException {
        System.out.println("INFO: Proxy started");
        new Thread(new Runnable() {

            @Override
            public void run() {
                Proxy.startThread();
            }

        }).start();
    }

    public static void startThread() {
        try {
            server = new ServerSocket(port);
            Socket clientSocket = server.accept();
            new Thread(new Server(originalHost)).start();
            new Thread(new Client(clientSocket)).start();
        } catch (Exception e) {
            System.out.println(e);
        }
    }


}

      

+3


source to share


1 answer


You need a single thread that starts a loop that checks the server socket for new connections by calling the accept () method on the ServerSocket. For each connection, you need to create a thread to handle that connection.

What your code actually does is check the server socket for a new connection by calling accept () exactly once. Then you correctly create a client thread to handle this connection. However, you have never called accept () yet. This is why your code works, but only for one client. You also create a stream for the Server object; I'm not sure how this fits in.



What you need to change is to run the "server.accept ()" statement and its associated thread in a loop. You also need to make sure that you are handling streams correctly so that different connections do not result in each other's data being consumed. This may require connecting your Server objects and Client objects in a certain way.

0


source







All Articles