Java Socket

How to use public api with java socket?

Hello @hyhong

on server side you can do something like,

 public static void main(String[] args) throws Exception {
        try (ServerSocket listener = new ServerSocket(8086)) {
            System.out.println("The capitalization server is running...");
            ExecutorService pool = Executors.newFixedThreadPool(20);
            while (true) {
                pool.execute(new Capitalizer(listener.accept()));
            }
        }
    }

    private static class Capitalizer implements Runnable {
        private Socket socket;

        Capitalizer(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            Transaction transaction = ElasticApm.startTransaction();
            transaction.setName("CapitalizerServer#run");
            transaction.setType(Transaction.TYPE_REQUEST);
            try {
                Scanner in = new Scanner(socket.getInputStream());
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                while (in.hasNextLine()) {
                    out.println(in.nextLine().toUpperCase());
                }
            } catch (Exception e) {
                transaction.captureException(e);
                System.out.println("Error:" + socket);
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                }
                System.out.println("Closed: " + socket);
                transaction.end();
            }
        }
    }

Thank you.But the client should have something like server side with public api.So,can former trace.

Hi @hyhong,

Socket instrumentation can't have distributed tracing because it requires to have some way to propagate trace context and sockets do not have such feature. While it would be possible to use the socket itself to propagate context, it would require to have both ends of the socket deployed with socket instrumentation to read and write context information, and that would likely have side effects both ends of the socket.

However, what agent does is to instrument higher-level protocols like HTTP, JMS, ... those provide a way for the client and server instrumentation to propagate context through headers or metadata.

In your case, what kind of service are you accessing through raw sockets ?
Is there any higher-level protocol (or communication library) that you could instrument here ?

Thank you.We only use socket to ommunication.I have seen the git:https://github.com/bvader/pipelineapmexample.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.