繁体   English   中英

客户端无法从服务器套接字编程Java接收消息

[英]Client not able to receive messages from Server Socket programming Java

我正在尝试通过终端制作聊天系统。 一台计算机充当服务器,另一台计算机充当客户端。

这是我的客户端代码:

try
    (
        Socket s = new Socket(hostname,port);
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
    ) {
        String input;

        while ((input = stdIn.readLine()) != null)
        {
            out.println(input);
        }


        String inputline;
        while ((inputline = in.readLine()) != null)
        {
            System.out.println("Them: " + inputline);
        }



        // out.close();
        // stdIn.close();
        // s.close();
    }
    catch (UnknownHostException e)
    {
        System.err.println("Don't know about host: " + hostname);
        System.exit(1);
    }
    catch (IOException e)
    {
        System.err.println("Couldn't get I/O");
        System.exit(1);
    }

这是我在服务器端的代码:

System.out.println ("New communication thread started.");
        try
        {
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String input;

            String inputline;
            while ((inputline = in.readLine()) != null)
            {
                System.out.println("Them: " + inputline);
            }

            while ((input = stdIn.readLine()) != null)
            {
                out.println(input);
            }
        }
        catch (IOException exx)
        {
            System.err.println("Some problem");
            System.exit(1);
        }

您正在System.in上使用stdIn.readLine() ,但是该流永远不会终止(当然)。 因此,您应该更改条件。

while ((input = stdIn.readLine()) != null) // Your problem is here

您是否检查过第二秒?

在服务器和客户端中都尝试此操作:

 input = stdIn.readLine();
 out.println(input);

暂无
暂无

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

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