Search code examples
javatcpgoogle-compute-engine

deploying java project to google compute engine


I had a tough time trying to deploy my Java project to Google cloud engine. I read most of Google cloud documentation but I still can't figure it out.

What I want is just tcp communication. I don't need the HTML itself to do something. A lot of guides talk about servlets and http get and post but I need just tcp. Maybe I lack of information and that is why I can't manage it.

So first - do I need some sort of http sever to run just tcp requests? And if not how can I deploy my project?

Right now my project has just Java. I used IntelliJ if it matters. It is something like that.

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class MainServer {

    public static void main(String[] args) {
        final int SERVER_PORT = 3000;
        final int SERVER_TIMEOUT = 5000;

        try (ServerSocket serverSocket = new ServerSocket(SERVER_PORT)) {
            while (true) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    clientSocket.setSoTimeout(SERVER_TIMEOUT);
                    new ClientThread(clientSocket).start();
                } catch (IOException ignored) {
                }
            }
        } catch (IOException ignored) {
        }
    }
}

And in ClientThread I work with every request.

I tried it locally and it works perfectly.

Now I just need to deploy this project somehow to the compute engine and make it work.

Additionally I installed Java JRE on the server. I hope port 3000 is ok if not I can change it.

Thanks in advance and sorry if I wasn't so clear.


Solution

  • Create a runnable JAR file. Copy it to your Compute Engine instance. Run it.

    If you want to be able to start/stop this program without logging into your instance, then you need a simple servlet. Look at the embedded Jetty - this is probably the best solution for this use case.