简体   繁体   English

Java无法获得客户端或服务器响应

[英]Java can't get client or server response

I'm from Poland, so I'm sorry for any mistakes. 我来自波兰,因此对任何错误深表歉意。
I've coding for a while a small server and client connection, when I stopped on annoying problem. 当我停止烦人的问题时,我已经为小型服务器和客户端连接编写了一段时间。 When I send from client to server information (String), server can get it, but can't respone to it. 当我从客户端向服务器发送信息(字符串)时,服务器可以获取它,但无法对其进行响应。

Here it is code. 这是代码。

Client 客户

private static Socket socket;

public static void main(String args[]){
    try{
       String host = "localhost";
       int port = 25002;
       InetAddress address = InetAddress.getByName(host);
       socket = new Socket();
       socket.connect(new InetSocketAddress(host, port), 5000);

       //Send the message to the server
       System.out.println("< "+sendMessage(socket));
       //socket.shutdownOutput();
       System.out.println("> "+getMessage(socket));
   }catch (SocketTimeoutException e){
      System.out.println(e.getMessage()); // changed
   }catch (IOException e){
      System.out.println(e.getMessage()); // changed
   }catch (IllegalBlockingModeException e){
      System.out.println(e.getMessage()); // changed
   }catch(IllegalArgumentException e){
      System.out.println(e.getMessage()); // changed
   }finally{
      //Closing the socket
      try{
         socket.close();
      }catch(Exception e){
         System.out.println(e.getMessage()); // changed
      }
   }
}

public static String sendMessage(Socket client){
    try {
        String message = "test";
        PrintWriter writer = new PrintWriter(client.getOutputStream(), true);
        writer = new PrintWriter(client.getOutputStream(), true);
        writer.print(message);
        writer.flush();
        writer.close();
        return message;
     } catch (IOException e) {
        System.out.println(e.getMessage()); // changed
        return "false";
     }
}

public static String getMessage(Socket client){
            try {
                BufferedReader socketReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
                return socketReader.readLine();
            } catch (IOException e){
                System.out.println(e.getMessage()); // changed
                return "false";
            }
        }

And.. server 和..服务器

public class kRcon{
        private static Socket socket;
        private static ServerSocket serverSocket;
        private static Thread u;

        private static class Server extends Thread {
                public void run() {
                        int port = 25002;
                        try {
                            serverSocket = new ServerSocket(port);
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        while(true) {
                          try {
                             socket = serverSocket.accept();
                             BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                             BufferedWriter socketWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                             String str = socketReader.readLine();
                        socketReader.close();
                             System.out.println(str);
                             socketWriter.write("test");
                             socketWriter.flush();
                             socketWriter.close();
                          }
                        }catch (IOException e1) {
                            e1.printStackTrace();
                        }
               }
         public static void init(){
         try {
            u = new Server();
            u.setName("Server");
            u.start();
        } catch (IOException e) {
            System.out.println(e.getMessage()); // changed
        }
    }
}

Results 结果
If, I start server first all looks nice. 如果可以,我首先启动服务器,一切看起来不错。 So, I start the client with parametr "test", nad output to console is: 因此,我使用参数“ test”启动客户端,输出到控制台的nad是:

< test
Socket is closed // changed

On server-side in console I have: 在控制台的服务器端,我有:

"test"
Socket is closed // changed

I tried to shutdown inputs and outputs and dosen't work.. I don't know to do now. 我试图关闭输入和输出,但没有用..我现在不知道该怎么做。 Please help :c 请帮忙:c

Edited 2015-04-03 编辑于2015-04-03
I've changed lines with comment "changed". 我已更改注释为“已更改”的行。

For Google, and readers To fix problem, don't close StreamReaders nad StreamWriters on client's sides. 对于Google和读者来说,要解决问题,请不要关闭客户端的StreamReaders nad和StreamWriters。 Thanks to EJP , for help! 感谢EJP的帮助!
Greetings from Poland. 来自波兰的问候。

When you get an exception, print it. 收到异常后,将其打印出来。 Don't just throw away all that information. 不要只是丢掉所有这些信息。 And don't return magic Strings either. 而且也不返回魔术Strings In this case you should have let the exception propagate. 在这种情况下,应该让异常传播。 If you had done all that you would have seen the exception SocketException: socket closed being thrown by getMessage(), and you would have had something concrete to investigate, instead of a complete mystery. 如果您已完成所有操作,您将看到SocketException: socket closed getMessage(),抛出了SocketException: socket closed getMessage(),您将需要进行一些具体的研究,而不是一个完整的谜。

It is caused by closing the PrintWriter in sendMessage(). 这是由于关闭sendMessage().PrintWriter引起的sendMessage(). Closing either the input or output stream of a socket closes the other stream and the socket. 关闭套接字的输入或输出流会同时关闭另一个流和套接字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM