簡體   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