Java客户端/服务器套接字程序 - 服务器不响应客户端请求

时间:2014-05-11 13:50:51

标签: java sockets

我正在尝试测试提供by Oracle的客户端/服务器教程示例,并进行了一些小的调整。

理想情况下,我会在我的客户端中将“print stuff”写入我的BufferedReader stdIn,服务器收到此字符串后会打印出“Client and server connected!”。

我的代码编译,似乎连接成功。但是,我的服务器此时没有打印任何内容。

以下是我的客户代码:

public class myClient {

public static void main(String[] args) throws IOException {

    String hostName = // my computer's local host name;
    int portNumber = 4444;

    try ( 
        Socket clientSocket = new Socket(hostName, portNumber);
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    ) {
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

        // Tell server to print line "Client and server have connected!";
        String fromServer;
        String fromUser;

        while ((fromServer = in.readLine()) != null) {
            if (fromServer.equals("End"))
                break;

            fromUser = stdIn.readLine();

            if (fromUser != null)
                out.println(fromUser);
        }

    } catch (UnknownHostException e) {
        System.err.println("Don't know host!");
        System.exit(1);
    } catch (IOException e) {
        System.err.println("IO Exception caught!");
        System.exit(1);
    }

}

}

以下是我的服务器代码:

public class myServer {

public static void main(String[] args) throws IOException {

    int portNumber = 4444;

    try (
        ServerSocket serverSocket = new ServerSocket(portNumber);
        Socket clientSocket = serverSocket.accept();

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    ) {

        // if receieved string is "print stuff", print "Client and server have connected!";
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            if (inputLine.equals("End"))
                break;

            // try to echo input stream - no output!
            out.println(inputLine);

            if (inputLine.equals("print stuff"))
                out.println("Client and server have connected!");
        }

    } catch(IOException e) {
        System.err.println("Exception caught while trying to listen to port!");
    }

}

}

1 个答案:

答案 0 :(得分:2)

第一个错误是您的客户端在连接后等待来自服务器的输入,但服务器不发送任何内容。因此,您的用户输入循环永远不会执行。

第二个错误是,只要您不输入“打印内容”,服务器就不会对客户端做出任何响应。所以客户端再次等待来自服务器的输入,即等待用户输入的instad。