1

私はソケットが初めてで、基本的にクライアントプログラムからサーバープログラムにいくつかの簡単なリクエストを送信できるプログラムを作成しようとしています。今は、ユーザーが選択できる 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();

ユーザー入力用とソケット用に 1 つずつ、Clinet に 2 つの異なる BufferedReaders が必要ですか? この部分については本当に混乱しています。

ありがとう

4

1 に答える 1

1

クライアントは、ユーザーからの入力を読み取り、それをサーバーに送信する必要があります。サーバーはソケットから読み取り、ソケットに応答する必要があります。クライアントはソケットから読み取り、ユーザーに適切なメッセージを送信する必要があります。サーバーは、クライアントを介してのみ、ユーザーに直接何も読み書きしません。

于 2012-09-05T17:32:46.433 に答える