Server listenning at port with endpoint

By | October 5, 2018
Questions:

I have created a server using sockets in Java and it is ready to receive HTTP requests and emit HTTP response.
The server is on a port of my PC, but I want to listen only into an “endpoint”, I mean, I want to mount the server i.e. on localhost:60802/json.
Is this possible? My code is here:

            PORT = Integer.parseInt(portSelection.getText());
            th =  new Thread(new Runnable() {

                //String file;
                @Override
                public void run() {
                    try{
                        server = new ServerSocket(PORT);

                        while(open) {
                            //Accept connections
                            connection = server.accept();

                            in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

                            try {
                                String line="";

                                while ((line=in.readLine())!= null && !line.equals("")){log.append(line);}                                                              
                                in.close();
                            }catch (Exception e1) {
                            }
                        }
                    }catch (EOFException e1 ) {
                        e1.printStackTrace();
                    }catch (BindException e1) {
                        log.setText("Error. Port "+PORT+" already in use.");
                        open=false;
                    }catch (SocketException e1) {

                    }catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            });
            th.start();

I have omitted some parts, so maybe you detect an error, but code works perfect at this time.

Answers:

Leave a Reply

Your email address will not be published. Required fields are marked *