1

我正在尝试编写一个程序,其中客户端请求服务器拥有的内核数。我这样做如下:

客户:

 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();
            }

        }

    });

服务器:

   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();
}

但是,当我加载服务器并点击运行客户端代码的 gui 上的按钮时,什么也没有发生,按钮只是卡住了。这是什么原因造成的?

谢谢你。

4

2 回答 2

0

结果是,当客户端上的代码正在等待一个字符串时,我发送了一个整数。

于 2013-08-02T16:00:47.357 回答
0
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();
于 2013-08-01T22:45:48.607 回答