Server / client communications do not work java

advertisements

I am trying to write a program in which the client requests the number of cores the server has. I do this as follows:

Client:

 public void actionPerformed(ActionEvent e) {
            try {
                Socket clientSocket = new Socket("128.59.65.200", 6789);
                DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
                BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                String numberOfCores = inFromServer.readLine();clientSocket.close();
                System.out.println(numberOfCores);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }

    });

Server:

   public static void sendNumberOfCores() {
    Thread coresThread = new Thread() {
        public void run() {
            try {
                int numberOfCores;
                ServerSocket welcomeSocket = new ServerSocket(6789);
                while (true) {
                    Socket connectionSocket = welcomeSocket.accept();
                    DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
                    numberOfCores = Runtime.getRuntime().availableProcessors();
                    outToClient.write(numberOfCores);
                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    };
    coresThread.setName("Wait for core request thread");
    coresThread.start();
}

However, when I load the server and hit the button on my gui which runs the client code, nothing happens and the button just gets stuck. What is causing this?

Thank you.


Server not initialized on the 6789 port and make sure you do that in a separate thread.
Some thing like this.

In Server class:
--Make an inner class say MyServer

    class MyServer implements Runnable{
        final int BACKLOG=10;    //10 is the backlog,if your server wishes to serve  requests.
        final int PORT = 6789;
        public void run(){
            try {  

                      ServerSocket serverSocket = new ServerSocket(PORT,BACKLOG);  //10 is the backlog,if your server wishes to serve conncurrent requests.

                while (true) {
                      Socket ClientConnetion = serverSocket.accept();

            //Now whatever you want to do with ClientConnection socket you can call

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
}

--Start this thread in you main server class

MyServer mys=new MyServer();
        Thread r=new Thread(mys);
        mys.start();