【问题标题】:Socket Communication Server/Client套接字通信服务器/客户端
【发布时间】:2012-08-30 11:38:41
【问题描述】:

我对 Sockets 有点陌生,我正在尝试编写一个程序,我基本上可以将一些简单的请求从客户端程序发送到服务器程序。现在我只想在客户端中有 1 或 2 个用户可以选择的选项。例如,如果用户在客户端中选择“选项 1”,那么服务器会发回一条消息“您选择选项 1”等等,但我不知道如何读取客户端发送的服务器上的输入。

客户代码:

Socket socket = null;

    try
    {
        System.out.println("Connecting to Server");

        socket = new Socket("192.168.0.104", 7003);
        socket.setSoTimeout(10000);
        System.out.println("Connected");

        InputStreamReader input = new InputStreamReader(socket.getInputStream());
        BufferedReader buffer = new BufferedReader(input);
        PrintWriter print = new PrintWriter(socket.getOutputStream(), true);

        String line = buffer.readLine();

        //Not Sure which buffer to user here            
        System.out.println("Option 1");
        System.out.println("Option 2");
        System.out.println("Option 3");
        }

        System.out.println("Closing Client Connection");
        buffer.close();
        input.close();
        print.close();
        socket.close();
        System.exit(0);

服务器代码:

    ServerSocket serverSock = null;
    Socket standSock = null;

    try
    {
        serverSock = new ServerSocket(7003);
        standSock = serverSock.accept();

        InputStreamReader input = new InputStreamReader(standSock.getInputStream());
        BufferedReader read = new BufferedReader(input);
        PrintWriter print = new PrintWriter(standSock.getOutputStream(), true);

        String dateTime = (Calendar.getInstance()).getTime().toString();
        print.println("You're connected to the Server at: " + dateTime);
        print.println("Type Q to disconnect");

        String line = read.readLine();
        //Not sure what to do here
        System.out.println("Client: " + line);
        print.println("Server" + line);


        System.out.println("Closing Server Connection");
        read.close();
        input.close();
        print.close();
        standSock.close();

我是否需要在 Clinet 中使用两个不同的 BufferedReader,一个用于用户输入,一个用于套接字?真的对这部分感到困惑。

谢谢

【问题讨论】:

    标签: java sockets


    【解决方案1】:

    客户端需要读取用户的输入并将其发送到服务器。服务器需要从套接字读取并响应套接字。客户端必须从套接字读取并向用户提供适当的消息。服务器不直接向用户读取或写入任何内容,仅通过客户端。

    【讨论】:

    • 所以在客户端我需要两个缓冲区,一个从用户读取输入,一个从套接字读取输入?
    • 正确。在客户端中,您还需要能够写入套接字和 System.out。
    • 您有一个 PrintStream 到套接字,另一个是为您提供的System.out。没有这样的魔法。只是客户端有两个输入和两个输出。
    • 你知道我可以看看这样的例子吗?
    • 数以千计的例子,但我想不出哪个完全符合您的要求。谷歌搜索java socket code 给出了 2000 万条结果。您必须调整现有示例以满足您的要求。
    猜你喜欢
    • 2012-11-02
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    相关资源
    最近更新 更多