即使没有异常启动,套接字也无法通信

时间:2018-12-01 18:58:30

标签: java string sockets reader

我正在尝试从客户端向服务器发送字符串,但是即使所有代码编译都没有错误并且没有抛出异常,也不会发送任何内容。这是我的服务器:

        String nomeAccount = "";
        try {
            //PHASE 1: The server receives the email
            try {
                InputStream inStream = incoming.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
                //if I print something here it works
                nomeAccount = in.readLine(); 
                //here nothing get printed
                System.out.println("Nome: "+nomeAccount);
            } catch (IOException ex) {
                System.out.println("Not works");
                Logger.getLogger(ServerController.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    incoming.close();
                } catch (IOException ex) {
                    System.out.println("Not works");
                    Logger.getLogger(ServerController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

这是客户:

//PHASE 1: The client sends a string to the server
    try {
        InputStream inStream = s.getInputStream();
        OutputStream outStream = s.getOutputStream();
        PrintWriter out = new PrintWriter(outStream, true);
        out.write(account+"\n");

1 个答案:

答案 0 :(得分:0)

有几个问题

  • PrintWriter吃掉所有异常。如果它们被扔了,您将看不到它们。
  • 使用PrintWriter而不是普通的Writer的目的是使用printlnprintprintf
  • 除非您打印新行,否则它不会刷新数据(应该与write()一起使用,但println更清晰)