客户端无法从Server Socket编程Java接收消息

时间:2016-04-26 17:56:04

标签: java sockets

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

以下是我的客户端代码:

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

1 个答案:

答案 0 :(得分:1)

您在stdIn.readLine()上使用System.in,但该流永远不会终止(当然)。 所以你应该改变你的状况。

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

你有没有检查过你的第二个?

在服务器和客户端中尝试:

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