Client Server按顺序交换消息

时间:2013-02-13 17:16:06

标签: java client-server serversocket

以下是我的服务器和客户端身份验证程序。我想知道我是以正确的方式做的,我希望消息按顺序发送和接收,这意味着,服务器只在收到客户端的输入后发送数据,同样的事情发送到客户端,收到服务器的响应后然后回复。

Client class:

try {
        // Set up the socket
        connection = new Socket("127.0.0.1", 55555);
        PrintWriter out = new PrintWriter(connection.getOutputStream(),
                true);
        BufferedReader in = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));

        // Client --> Server 'A'
        BigInteger A = client.Step1(username, password);
        out.println(A);
        // Client received s , B
        byte[] s = new BigInteger(in.readLine()).toByteArray();
        BigInteger B = new BigInteger(in.readLine());
        // Client --> Server 'A'
        BigInteger M1 = client.Step2(new BigInteger(s), B);
        out.println(M1);
        // Client received M2
        BigInteger M2 = new BigInteger(in.readLine());

        boolean clientVerify = client.clientVerify(M2);
        if (clientVerify) {
            System.out.println("Client OK");
        } else {
            System.out.println("NOT OK");
        }

        out.close();
        in.close();
        connection.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

Server class:
try {
        socServer = new ServerSocket(55555);
        System.out.println("Waiting Client....");
        connection = socServer.accept();
        System.out.println("Client Connected");

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

        // Server received A
        BigInteger A = new BigInteger(in.readLine());
        // Server --> Client 's' , 'B'
        out.println(new BigInteger(s));
        BigInteger B = server.step1(username, new BigInteger(s), v);
        out.println(B);
        server.step2(A);

        // Server received 'M1'
        BigInteger M1 = new BigInteger(in.readLine());
        boolean serverVerify = server.serverVerify(M1);
        if (serverVerify) {
            // Server --> Client 'M2'
            BigInteger M2 = server.step2(A, M1);
            out.println(M2);
            System.out.println("Server OK");
        } else {
            System.out.println("NOT OK");
            connection.close();
        }

        out.close();
        in.close();
        connection.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

我能通过Wireshark捕获数据吗?

0 个答案:

没有答案